<template>
    <div class="index" id="index">
        <div class="side_bar left">
          <!-- <router-link v-for="(item,ind) in sideData" tag="div" key="ind" :to="item.url" active-class="active_class" class="side_bar_item">
                    <span v-text='item.name'></span>
                </router-link> -->
            <div class="logo flex flex-align-center flex-pack-center">
                <div class="logo-img">
                    <img src="../../assets/logo.png" height="186" width="210" alt="">
                </div>
            </div>
            <router-link active-class="active_class" to="/cashier" tag="div" :key="1" class="side_bar_item flex flex-align-center flex-pack-center">
                <div>
                    <div><i class="iconfont icon-shouyin"></i></div>
                    <div><span>收银</span></div>
                </div>
            </router-link>
            <router-link active-class="active_class" to="/order" tag="div" :key="2" class="side_bar_item flex flex-align-center flex-pack-center ">
                <div>
                    <div class="order-icon">
                        <i class="iconfont icon-dingdan"></i>
                        <span class="num" v-text="'!'" :style="{'display':(orderNum>0?'block':'none')}"></span>
                    </div>
                    <div><span>订单</span></div>
                </div>
            </router-link>
            <div class="side_bar_item flex flex-align-center flex-pack-center" @click="vipBoxBtn=true">
                <div>
                    <div class="order-icon">
                        <i class="iconfont icon-vip"></i>
                    </div>
                    <div><span>会员</span></div>
                </div>
            </div>
            <router-link class="side_bar_item flex flex-align-center flex-pack-center" to="/exchangeWork" tag="div" :key="3" active-class="active_class">
                <div>
                    <div><i class="iconfont icon-jiaoban"></i></div>
                    <div><span>交班</span></div>
                </div>
            </router-link>
            <router-link v-if="offOnVoiceNotify" class="side_bar_item flex flex-align-center flex-pack-center" to="/onlineCord" tag="div" :key="3" active-class="active_class">
                <div>
                    <div><i class="iconfont icon-lixian"></i></div>
                    <div><span>下机</span></div>
                </div>
            </router-link>
            <!-- <router-link class="side_bar_item flex flex-align-center flex-pack-center" to="/checkBill" tag="div" :key="4" active-class="active_class">
                <div>
                    <div><i class="iconfont icon-zhangdan"></i></div>
                    <div><span>对账单</span></div>
                </div>
            </router-link> -->
            <div class="side_bar_item flex flex-align-center flex-pack-center" @click="setting">
                <div>
                    <div><i class="iconfont icon-set"></i></div>
                    <div><span>设置</span></div>
                </div>
            </div>
            <!-- <div class="side_bar_item flex flex-align-center flex-pack-center" @click="goInv">
                <div>
                    <div><i class="iconfont icon-chakankucun"></i></div>
                    <div><span>库存</span></div>
                </div>
            </div> -->
        </div>
        <div class="index_route_box right">
            <div class="top">
                <div class="dateBox clearfix left dateBoxCenter">
                    <span class="flex flex-align-center left">欢迎光临</span>
                    <span class="flex flex-align-center left" v-text="storeInfo.storeName"></span>
                    <span class="flex flex-align-center left" style="font-size:14px;color:#27a9f4;">{{endDay>0?'到期时间：'+endTime:'已过期'+Math.abs(endDay)+'天，请联系服务人员续费。'}}</span>
                </div>
                <div class="dateBox clearfix right userNotSelect">
                    <span class="flex flex-align-center left logout" @click="showConfirmMask=true">[退出]</span>
                    <!-- <span class="flex flex-align-center left span" v-text="employeeInfo.operatorName"></span> -->
                    <div class="flex flex-align-center date left">
                        <div v-text="dateStr"></div>
                        <div class="time" ><span v-text="weekStr" style="margin-right:5px;"></span><span v-text="timeStr"></span></div>
                    </div>
                </div>
                <!-- <div class="position-middle-center right" style="width:300px;"> -->
                <div class="right" style="width:200px;height:100%;display:flex;align-items:center;margin-right:50px;">
                    <!-- <marquee direction="left" align="bottom" height="25" width="100%" onmouseout="this.start()" onmouseover="this.stop()" scrollamount="4" scrolldelay="1" style="font-size:18px;">{{endDay>0?'距离到期还有'+endDay+'天':'已过期'+Math.abs(endDay)+'天，请联系服务人员续费。'}}</marquee> -->
                    <marquee direction="left" align="bottom" height="25" width="100%" onmouseout="this.start()" onmouseover="this.stop()" scrollamount="4" scrolldelay="1" style="font-size:18px;">温馨提示：开班后，须在24小时内进行交班，否则将不会统计数据！</marquee>
                </div>
                <!-- <div class="position-middle-center announce" style="width:450px">
                    <marquee direction="up" align="bottom" height="25" width="100%" onmouseout="this.start()" onmouseover="this.stop()" scrollamount="1" scrolldelay="1" style="font-size:18px;">升级公告：8月18日（星期六）凌晨4点至5点，火星捕手服务器硬件升级，升级期间，访问会出现中断，请收银员做好准备，谢谢！</marquee>
                </div> -->
                <!-- <div class="dateBox clearfix right">
                    <span class="flex flex-align-center logout" @click="noticeCurrentPage=1 ;getNoticeFn(1)">服务</span>
                </div> -->
            </div>
            <div class="index_route_inner">
                <router-view
                    :storeId="storeInfo.storeId"
                    :storeName="storeInfo.storeName"
                    :printsBtn="printsBtn"
                    :orderNum="orderNum"
                    :waitNum="waitNum"
                    :leaseNum="leaseNum"
                    :isOnline="isOnline"
                    :endTime="endTime"
                    :isPrintPrev="isPrintPrev"
                    @refresh="getNewNum"
                    >
                </router-view>
            </div>
        </div>

        <div class="mask" v-if="showConfirmMask" @click="showConfirmMask=false">
            <div class="orderConfirmBox" @click.stop="">
                <div class="title">提示</div>
                <p>确认退出当前账号？</p>
                <div class="btnGroup">
                    <button type="button" class="cancel" @click="showConfirmMask=false">取消</button>
                    <button type="button" class="save" @click="logout">确认</button>
                </div>
            </div>
        </div>

        <div class="vipBox" v-if="vipBoxBtn" @click="vipBoxBtn = false">
            <div class="content position-middle-center clearfix" @click.stop="()=>{}">
                <div class="item left flex flex-align-center flex-pack-center" @click.stop="addVip">
                    <div>
                        <div class="i_pre">
                            <i class="iconfont icon-adduser"></i>
                            <!-- <span style="font-size:25px;">+</span> -->
                        </div>
                        <p>添加</p>
                    </div>
                </div>
                <div class="item left flex flex-align-center flex-pack-center" @click.stop="rechargeFn">
                    <div>
                        <div class="i_pre">
                            <i class="iconfont icon-shouyin"></i>
                        </div>
                        <p>充值</p>
                    </div>
                </div>
                <div class="item left flex flex-align-center flex-pack-center" @click.stop="openSendCouponBox">
                    <div>
                        <div class="i_pre">
                            <svg t="1685609771596" class="icon" viewBox="0 0 1024 1024" fill="#e66a6a" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3459" width="40" height="40"><path d="M772.266667 64C738.133333 4.266667 657.066667-17.066667 597.333333 17.066667l-170.666666 98.133333-29.866667-17.066667C332.8 64 256 81.066667 221.866667 145.066667L72.533333 405.333333h896l-196.266666-341.333333z m-132.266667 29.866667c21.333333-12.8 46.933333-4.266667 59.733333 17.066666l140.8 247.466667L512 170.666667l128-76.8zM170.666667 362.666667l106.666666-183.466667c17.066667-29.866667 55.466667-42.666667 85.333334-21.333333l85.333333 51.2L725.333333 362.666667H170.666667z" fill="#e66a6a" p-id="3460"></path><path d="M426.666667 554.666667h170.666666c25.6 0 42.666667 17.066667 42.666667 42.666666s-17.066667 42.666667-42.666667 42.666667h-170.666666c-25.6 0-42.666667-17.066667-42.666667-42.666667s17.066667-42.666667 42.666667-42.666666zM426.666667 721.066667h170.666666c25.6 0 42.666667 21.333333 42.666667 42.666666s-21.333333 42.666667-42.666667 42.666667h-170.666666c-25.6 0-42.666667-21.333333-42.666667-42.666667s21.333333-42.666667 42.666667-42.666666z" fill="#e66a6a" p-id="3461"></path><path d="M904.533333 682.666667c0-46.933333 21.333333-89.6 55.466667-115.2V469.333333c0-34.133333-29.866667-64-64-64H128c-34.133333 0-64 29.866667-64 64v85.333334c42.666667 25.6 72.533333 72.533333 72.533333 128s-29.866667 102.4-72.533333 128v85.333333c0 34.133333 29.866667 64 64 64h768c34.133333 0 64-29.866667 64-64v-98.133333c-34.133333-25.6-55.466667-68.266667-55.466667-115.2z m119.466667 213.333333c0 72.533333-55.466667 128-128 128H128c-72.533333 0-128-55.466667-128-128v-128c38.4-8.533333 72.533333-42.666667 72.533333-85.333333S42.666667 605.866667 0 597.333333v-128c0-72.533333 55.466667-128 128-128h768c72.533333 0 128 55.466667 128 128v132.266667c-34.133333 12.8-55.466667 42.666667-55.466667 81.066667 0 38.4 25.6 68.266667 55.466667 81.066666V896z" fill="#e66a6a" p-id="3462"></path></svg>
                        </div>
                        <p>派券</p>
                    </div>
                </div>
            </div>
        </div>
        <!-- 添加会员弹框 -->
        <div class="qrCodeBox" v-if="qrCodeBtn" @click="qrCodeBtn = false">
            <div class="qrCode position-middle-center" @click.stop="()=>{}">
                <div class="close-btn" @click.stop="()=>{qrCodeBtn = false;}">&times;</div>
                <div class="title">
                    添加会员
                </div>
                <div class="form">
                    <div class="tit" style="padding-bottom:10px;font-weight:bold;">方式一：</div>
                    <el-form :model="vipForm" label-position="top" label-width="80px">
                        <el-form-item label="手机号" required>
                            <el-input v-model="vipForm.mobile" placeholder="请输入手机号"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input v-model="vipForm.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="" style="margin-top:10px">
                            <el-button style="width:100%" @click.stop="submitVip" type="primary">确定</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="tit two" style="padding-left:50px;padding-top:10px;font-weight:bold;">方式二：</div>
                <div class="content" style="margin-top:20px">
                    <div id="qrcode"></div>
                </div>
                <p class="qrcode-text">微信扫码并关注“火星捕手”即可成为会员</p>
            </div>
        </div>
        <div class="rechargeBox" v-if="rechargeBoxBtn" @click="rechargeBoxBtn = false">
            <div class="recharge position-middle-center" @click.stop="()=>{}">
                <div class="closeBtns" @click="rechargeBoxBtn = false">&times;</div>
                <div class="title">会员充值</div>
                <div v-if="!inputVipCodeBtn">
                    <div class="vipMsg clearfix">
                        <div class="name left">会员名称：</div>
                        <div class="val left" v-text="curSelectVipData.name"></div>
                    </div>
                    <div class="vipMsg clearfix">
                        <div class="name left">会员帐号：</div>
                        <div class="val left" v-text="curSelectVipData.mobile?curSelectVipData.mobile:curSelectVipData.code"></div>
                    </div>
                    <div class="vipMsg clearfix">
                        <div class="name left">会员余额：</div>
                        <div class="val left" v-text="'￥'+curSelectVipData.amount"></div>
                    </div>
                    <div class="selMoneyBox">
                        <div class="recharge-scroll-box" v-if="!vipPayBtn">
                            <div class="item" v-for="item in rulesData" @click="choiceRules(item)"><span v-text="item.name"></span></div>
                            <div class="input-recharge">
                                <div class="clearfix" v-if="MorePayBtn">
                                    <span class="left">自定义金额：</span>
                                    <input class="left" type="text" placeholder="请输入充值金额" v-model="inputVipMoney">
                                </div>
                                <div class="clearfix" v-if="!MorePayBtn">
                                    <button type="button" @click="MorePayBtn=true">更多充值规则</button>
                                </div>
                            </div>
                        </div>
                        <div class="btnGroup" v-if="!vipPayBtn">
                            <button type="button" class="cancel" @click="rechargeBoxBtn=false">取消</button>
                            <button type="button" class="save" @click="choiceRules()">确认</button>
                        </div>

                        <div class="vipPayBox" v-if="vipPayBtn">
                            <div class="top_money">
                                <div class="returnBtn">
                                    <div class="left flex flex-align-center" @click="vipPayBtn=false">
                                        <i class="iconfont icon-fanhui"></i>
                                        <span>返回</span>
                                    </div>
                                </div>
                                <div class="totalPrice flex flex-align-center flex-pack-center" v-text="'￥'+(inputVipMoney?inputVipMoney:(vipObj.depositAmount?vipObj.depositAmount:0))"></div>
                                <div class="serialNumber flex flex-align-center">
                                    <span class="name">流水号</span>
                                    <span v-text="vipObj.code"></span>
                                </div>
                            </div>
                            <p class="selPayType flex flex-align-center">选择支付方式</p>
                            <div class="pay_type clearfix">
                                <span class="left size1" :class="{span_active:payVipType == 'CASH'}"><input name="Fruit" type="radio" value="CASH" v-model="payVipType">现金支付</span>
                                <span v-if="isOnline" class="left size1" @click="openPayCodeBox()" :class="{span_active:payVipType == 'PAYCARD'}"><input name="Fruit" type="radio" value="PAYCARD" v-model="payVipType">在线支付</span>

                                <span v-if="!isOnline" class="left size1" :class="{span_active:payVipType == 'ALIPAY_CASH'}"><input name="Fruit" type="radio" value="ALIPAY_CASH" v-model="payVipType">支付宝支付</span>
                                <span v-if="!isOnline" class="left size1" :class="{span_active:payVipType == 'WECHATPAY_CASH'}"><input name="Fruit" type="radio" value="WECHATPAY_CASH" v-model="payVipType">微信支付</span>
                            </div>
                            <div  class="sure_pay">
                                <button @click="vipPayFn" type="button">确认支付</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="inputVipCode" style="width:420px;height:80px;" v-if="inputVipCodeBtn">
                    <div class="vip_up">
                        <div class="vipInputBox flex flex-align-center">
                            <input type="text" class="vipInput" v-model="vipNumber" placeholder="输入会员账号">
                            <!-- <button type="button" @click="addVipFn">确认</button> -->
                        </div>
                        <ul class="vipCheckList">
                            <div class="leftIcon" :style="{top:(curVipIdx*40+'px'),display:(vipList[0]?'block':'none')}"></div>
                            <li v-for="item in vipList" @click.stop="addVipFn(item)">
                                <div class="left name" v-text="item.name"></div>
                                <div class="right tel" v-text="item.mobile?item.mobile:item.code"></div>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="userPayCodeBox" v-if="showPayCodeBox">
            <form class="userPayCode" @submit.prevent="vipPayFn">
                <div class="tipText">
                    * 请输入或者扫描用户付款码
                </div>
                <div class="inputBox">
                    <input type="text" id="payCodeInput" autocomplete="off" v-model="payCode">
                </div>
                <div class="btnGroup">
                    <button type="submit" class="save">确认</button>
                    <button type="button" class="cancel" @click="showPayCodeBox=false">取消</button>
                </div>
            </form>
        </div>
        <div class="mask" v-if="showOnLinePaySuccessMask" @click="showOnLinePaySuccessMask=false">
            <div class="orderConfirmBox" @click.stop="">
                <div class="title">提示</div>
                <p>支付成功！</p>
                <div class="btnGroup">
                    <button type="button" class="save" @click="showOnLinePaySuccessMask=false">确认</button>
                </div>
            </div>
        </div>
        <div class="payLoding" v-if="showPayLoding">
            <div class="payLodeBox">
                <div class="payLoadImg">
                    <i class="iconfont icon-looding"></i>
                </div>
                <p v-if=" payVipType == 'PAYCARD'">支付中，请等待！</p>
                <p v-if=" payVipType == 'PAYCARD'">请在3分钟内完成支付，超时将自动取消。</p>
                <div class="btnGroup" v-if="payVipType == 'PAYCARD'">
                    <button type="button" class="cancel" @click="deleteOrder(vipObj.ordersId)">取消支付</button>
                    <button type="button" class="save" @click="aNewOrder">挂起此单</button>
                </div>
            </div>
        </div>

        <div class="mask" v-if="showSetting" @click="showSetting=false">
            <div class="settingBox" @click.stop="">
                <div class="title">系统设置</div>
                <div class="setInnter clearfix">
                    <div class="setItem">
                        <span class="name left">打印收银小票：</span>
                        <select name="" id="" v-model="settingObj.autoPrint">
                            <option value="ON">开</option>
                            <option value="OFF">关</option>
                        </select>
                    </div>
                    <div class="setItem" v-if="leaseProductEnabled">
                        <span class="name left">打印租赁小票：</span>
                        <select name="" id="" v-model="settingObj.printRentOrder">
                            <option value="ON">开</option>
                            <option value="OFF">关</option>
                        </select>
                    </div>
                    <!-- <div class="setItem" style="display: flex;">
                        <span class="name left">允许自动打印小票：</span>
                        <div style="display:flex;align-items: center;">
                            <input type="checkbox" name="" v-model="settingObj.isAutoPrintOrder" class="tag-print" id="" />
                            <div style="width:100%;font-size:12px;">如开启非现金结账的订单会自动打印票据</div>
                        </div>
                    </div> -->
                    <div class="setItem">
                        <span class="name left">交班小票分类打印：</span>
                        <select name="" id="" v-model="settingObj.totalClassify">
                            <option value="DETAILARRTYPE">所有分类+详细商品</option>
                            <!-- <option value="DETAILARR">仅详细商品</option> -->
                            <option value="ONETYPE">仅一级分类</option>
                            <option value="ONETOWTYPE">仅一二级分类</option>
                        </select>
                    </div>
                    <div class="setItem" style="display:none;">
                        <span class="name left">标签打印机名称：</span>
                        <input type="text" v-model="settingObj.pasterName">
                    </div>
                    <!-- <div class="setItem">
                        <span class="name left">标签打印机ID：</span>
                        <input type="text" v-model="settingObj.printId" placeholder="如：vid_0483&pid_070b">
                    </div> -->
                    <div class="setItem">
                        <span class="name left">是否允许标签打印：</span>
                        <input type="checkbox" name="" v-model="settingObj.isTagPrint" class="tag-print" id="" />
                        <span style="font-size:12px;">如开启则必须设置小票和标签的硬件ID</span>
                        <!-- <input type="text" v-model="settingObj.printId" placeholder="如：vid_0483&pid_070b"> -->
                    </div>
                    <!-- <div class="setItem">
                        <span class="name left">手动输入打印机ID：</span>
                        <select name="" id="" v-model="settingObj.handlePrint">
                            <option value="ON">开</option>
                            <option value="OFF">关</option>
                        </select>
                    </div> -->
                    <div class="setItem" v-if="settingObj.isTagPrint">
                        <span class="name left">标签打印机id：</span>
                        <input type="text" style="width:180px" v-if="handlePrint" v-model="settingObj.printIdForTag" placeholder="如：vid_0483&pid_070b">
                        <select name="" id="" style="width:180px" v-else v-model="settingObj.printIdForTag">
                            <option key="-1" value="">请选择</option>
                            <option v-for="(it,ind) in printDevices" :key="ind" :value="it">{{ it }}</option>
                        </select>
                        <button style="margin-left:10px;height:30px;" @click.stop="testTagPrint">测试</button>
                    </div>
                    <div class="setItem" v-if="settingObj.isTagPrint">
                        <span class="name left">小票打印机id：</span>
                        <input type="text" v-if="handlePrint" style="width:180px" v-model="settingObj.printIdForSale" placeholder="如：vid_0483&pid_070b">
                        <select name="" id="" style="width:180px" v-else v-model="settingObj.printIdForSale">
                            <option key="-1" value="">请选择</option>
                            <option v-for="(it,ind) in printDevices" :key="ind" :value="it">{{it}}</option>
                        </select>
                        <button style="margin-left:10px;height:30px;" @click.stop="testPrint">测试</button>
                    </div>
                    <div class="setItem">
                        <span class="name left">厨房打印Ip：</span>
                        <input type="text" v-model="settingObj.kitchIp" placeholder="如：192.168.123.100">
                    </div>
                    <div class="setItem">
                         <span class="name left">厨房打印端口：</span>
                        <input type="text" v-model="settingObj.kitchPort" placeholder="如：9100">
                    </div>
                    <div class="setItem">
                         <span class="name left">厨房默认打印份数：</span>
                        <input type="text" v-model="settingObj.kitchPrintCount" placeholder="默认打印两份">
                    </div>
                    <!--  -->
                    <template v-if="voiceEnabled">
                        <div class="setItem" style="display:flex;">
                            <span class="name left">订单音频输出设备：</span>
                            <select name="" id="" style="width:180px" v-model="audioDevice" placeholder="请选择">
                                <option 
                                v-for="(item,index) in audioOptions"
                                :key="index"
                                :label="item.label?item.label:`设备${index+1}`"
                                :value="item.label"
                                ></option>
                            </select>
                            <button style="margin-left:10px;height:30px;" @click.stop="testAudio('order')">测试</button>
                            <!-- <el-select v-model="audioDevice" placeholder="请选择">
                                <el-option
                                v-for="(item,index) in audioOptions"
                                :key="index"
                                :label="item.label?item.label:`设备${index+1}`"
                                :value="item.deviceId">
                                </el-option>
                            </el-select> -->
                        </div>
                        <!--  -->
                        <div class="setItem" style="display:flex;">
                            <span class="name left">下机音频输出设备：</span>
                            <!-- <el-select v-model="audioDeviceForOffline" placeholder="请选择">
                                <el-option
                                v-for="(item,index) in audioOptions"
                                :key="index"
                                :label="item.label?item.label:`设备${index+1}`"
                                :value="item.deviceId">
                                </el-option>
                            </el-select> -->
                            <select name="" id="" style="width:180px" v-model="audioDeviceForOffline" placeholder="请选择">
                                <option 
                                v-for="(item,index) in audioOptions"
                                :key="index"
                                :label="item.label?item.label:`设备${index+1}`"
                                :value="item.label"
                                ></option>
                            </select>
                            <button style="margin-left:10px;height:30px;" @click.stop="testAudio('Offline')">测试</button>
                        </div>
                    </template>
                    <!--  -->
                    <div class="setItem">
                        <span class="name left">订单提示音：</span>
                        <select name="" id="" v-model="settingObj.orderVoiceName" @change="selVoice">
                            <option value="voice_1.ogg">voice_1.ogg</option>
                            <option value="voice_1_1.ogg">voice_1_1.ogg</option>
                            <option value="voice_2.ogg">voice_2.ogg</option>
                            <option value="voice_3.ogg">voice_3.ogg</option>
                            <option value="voice_4.ogg">voice_4.ogg</option>
                            <option value="voice_5.ogg">voice_5.ogg</option>
                            <option value="voice_6.ogg">voice_6.ogg</option>
                            <option value="voice_7.ogg">voice_7.ogg</option>
                            <option value="voice_8.ogg">voice_8.ogg</option>
                            <option value="voice_9.ogg">voice_9.ogg</option>
                            <option value="voice_10.ogg">voice_10.ogg</option>
                        </select>
                    </div>
                    <!--  -->
                    <div class="setItem">
                        <span class="name left">支付到账音量大小：</span>
                        <div class="right-cont">
                            <el-slider v-model="settingObj.payVoiceVolum"></el-slider>
                        </div>
                    </div>
                    <div class="setItem">
                        <span class="name left">订单提示音量大小：</span>
                        <div class="right-cont">
                            <el-slider v-model="settingObj.orderVoiceVolum"></el-slider>
                        </div>
                    </div>
                    <div class="setItem">
                        <span class="name left">下机播报音量大小：</span>
                        <div class="right-cont">
                            <el-slider v-model="settingObj.offlineVoiceVolum"></el-slider>
                        </div>
                    </div>
                    <!--  -->
                </div>
                <div class="btnGroup">
                    <button type="button" class="cancel" @click="showSetting=false">取消</button>
                    <button type="button" class="save" @click="saveSetting()">确认</button>
                </div>
            </div>
        </div>
        <div class="mask " v-if="noticeBtn" @click="noticeBtn=false">
            <div class="settingBox notice" @click.stop="" style="width:680px;">
                <div class="title">呼叫历史</div>
                <div class="noticeBox">
                    <div class="item">
                        <span style="width:10%;"  class="left">序号</span>
                        <span style="width:30%;" class="left">座位号</span>
                        <span style="width:60%;" class="right">时间</span>
                    </div>
                    <div v-for="(item,ind) in noticeList" class="item clearfix">
                        <span style="width:10%;" v-text="(noticeCurrentPage-1)*10+ind+1" class=" left"></span>
                        <span style="width:30%;" v-text="item.tableNo" class=" left"></span>
                        <span style="width:60%;"  class=" right">{{item.addTime | numberToAllDate('')}}</span>
                    </div>
                </div>
                <div class="pagers">
                <el-pagination
                    @current-change="getNoticeFn"
                    :current-page.sync="noticeCurrentPage"
                    :page-size="10"
                    layout="total, prev, pager, next, jumper"
                    :total="noticeTotalElements">
                </el-pagination>
                </div>
            </div>
        </div>
        <div style="display: none" id="speech_voice_index" v-text="voice_text_index"></div>
        <div style="display: none" id="notice_voice" v-text="voice_text_notice"></div>
        <audio style="display:none" controls="" class="audio" src="../../../static/voice/default.m4a" autoplay="" id="audios"></audio>
        <!--  -->
        <!-- <el-dialog
        title="派发优惠券"
        class="coupon-mask"
        :visible.sync="showSendCouponBox"
        :before-close="closeCouponBox">
            <div class="send-box-wrap">
                <div class="coupon-item" v-for="it in couponList" @click.stop="toDsbtCoupon(it)" :key="it.id">
                    <div class="top">
                        <div class="coupon-image">
                            <img :src="it.logoURL" alt="">
                        </div>
                        <div class="coupon-desc">
                            <div class="coupon-name">
                                {{it.title}}
                            </div>
                            <div class="coupon-type">
    							{{couponType[it.type]}}
                            </div>
                            <div class="goods">
                                <el-popover
                                    :key="it.id"
                                    placement="left-start"
                                    title="可用商品"
                                    width="200"
                                    trigger="hover"
                                    :content="it.productName"
                                >
                                <span slot="reference" class="wen">?</span>
                                </el-popover>
                                <span>{{it.productName}}</span>
                            </div>
                            <div class="time">
                                有效日期:<span>{{new Date(it.startTime).Format("yyyy/MM/dd")}}~{{new Date(it.endTime).Format("yyyy/MM/dd")}}</span>
                            </div>
                        </div>
                        <span class="circle one"></span>
                        <span class="circle two"></span>
                    </div>
                    <div class="bottom rule">
                        <el-popover
                            :key="it.id"
                            placement="left-start"
                            title="使用规则"
                            width="200"
                            trigger="hover"
                            :content="it.notice"
                        >
                           <span slot="reference" class="wen">?</span>
                        </el-popover>
                        使用规则:{{it.notice}}
                    </div>
                    <div class="dsbt">
                        <span class="btn dsbt-btn" @click.stop="dsbtCoupon(it)">派发</span>
                    </div>
                </div>
            </div>
        </el-dialog> -->
        <!--  -->
        <div class="coupon-mask-wrap" v-if="showSendCouponBox" @click.stop="showSendCouponBox=false">
            <div class="send-box-wrap" :class="{one:couponList.length==1,other:couponList.length>1}">
                <div class="coupon-item" v-for="it in couponList" @click.stop="toDsbtCoupon(it)" :key="it.id">
                    <div class="top">
                        <div class="coupon-image">
                            <img :src="it.logoURL" alt="">
                        </div>
                        <div class="coupon-desc">
                            <div class="coupon-name">
                                {{it.title}}
                            </div>
                            <div class="coupon-type">
    							{{couponType[it.type]}}
                            </div>
                            <div class="goods">
                                <el-popover
                                    :key="it.id"
                                    placement="left-start"
                                    title="可用商品"
                                    width="200"
                                    trigger="hover"
                                    :content="it.productName"
                                >
                                <span slot="reference" class="wen">?</span>
                                </el-popover>
                                <span>{{it.productName}}</span>
                            </div>
                            <div class="time">
                                有效日期:<span>{{new Date(it.startTime).Format("yyyy/MM/dd")}}~{{new Date(it.endTime).Format("yyyy/MM/dd")}}</span>
                            </div>
                        </div>
                        <span class="circle one"></span>
                        <span class="circle two"></span>
                    </div>
                     <!-- <el-tooltip class="item" effect="dark" :content="it.notice" placement="top-end">
                        
                    </el-tooltip> -->
                    <div class="bottom rule">
                        <el-popover
                            :key="it.id"
                            placement="left-start"
                            title="使用规则"
                            width="200"
                            trigger="hover"
                            :content="it.notice"
                        >
                           <span slot="reference" class="wen">?</span>
                        </el-popover>
                        使用规则:{{it.notice}}
                    </div>
                    <!-- <div class="dsbt" v-if="nowSelCouponItem && nowSelCouponItem.id == it.id"> -->
                    <div class="dsbt">
                        <!-- <span class="btn cancel" @click.stop="clearCoupon">取消</span> -->
                        <span class="btn dsbt-btn" @click.stop="dsbtCoupon(it)">派发</span>
                    </div>
                </div>
            </div>
        </div>
        <!--  -->
        <el-dialog
        title="选择会员，派发优惠券"
        :visible.sync="showDsbtCoupon"
        width="35%"
        :close-on-click-modal="false"
        :before-close="clearCoupon">
        <template v-if="nowSelCouponItem">
            <div class="form-wrap">
                <div class="dsbt-coupon-info">
                    <div class="tit">{{nowSelCouponItem.title}}</div>
                    <div class="type">优惠券类型：{{couponType[nowSelCouponItem.type]}}</div>
                    <div class="time">有效日期：{{new Date(nowSelCouponItem.startTime).Format("yyyy/MM/dd")}}~{{new Date(nowSelCouponItem.endTime).Format("yyyy/MM/dd")}}</div>
                    <div class="goods">
                        <el-popover
                            placement="left-start"
                            title="可用商品"
                            width="200"
                            trigger="hover"
                            :content="nowSelCouponItem.productName"
                        >
                        <span slot="reference" class="wen">?</span>
                        </el-popover>
                        抵扣商品：{{nowSelCouponItem.productName}}</div>
                </div>
                <div class="dsbt-form">
                    <el-form>
                        <el-form-item label="请选择优惠券数量">
                            <el-select v-model="couponCount" 
                            style="width:100%"
                            placeholder="请选择优惠券数量">
                                <el-option
                                v-for="item in 30"
                                :key="item"
                                :label="item"
                                :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="输入手机号选择会员">
                            <el-select
                                style="width:100%"
                                v-model="nowSelVips"
                                multiple
                                filterable
                                remote
                                placeholder="请输入手机号"
                                :remote-method="remoteMethod"
                                :loading="loading">
                                <el-option
                                    v-for="item in members"
                                    :key="item.id"
                                    :label="`${item.name}(${item.mobile})`"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </template>
        
        <span slot="footer" class="dialog-footer">
            <el-button @click="showDsbtCoupon = false">取 消</el-button>
            <el-button type="primary" @click="submitDsbt">确 定</el-button>
        </span>
        </el-dialog>
        <div id="qrcode" style="display:none;"></div>
    </div>
</template>
<script type="text/javascript">
import API_BASE_URL,{WS_API_URL} from "./../../urlConfig/index";
import emitter from "@/bus/index";

export default{
    data(){
        return {
            leaseProductEnabled:false,
            posCallEnabled:true,
            handlePrint:true,
            printDevices:[],//打印机列表
            isAutoPrintOrder:false,
            printCount:0,
            canPrint:true,
            toPrintArr:[],
            // 
            curOrderData:{},
            isCostPrintBtn:false,//网费答应
            voiceEnabled:false,
            allAudioOptions:[],
            audioDeviceForOffline:"",
            audioDevice:"",
            audioOptions:[],
            // 
            offOnVoiceNotify:false,
            canClick:true,
            couponCount:"",
            nowSelVips:[],
            showDsbtCoupon:false,
            nowSelCouponItem:null,
            showSendCouponBox:false,
            // 
            payVoiceVolum:100,
            orderVoiceVolum:100,
            offlineVoiceVolum:100,
            // 
            codeInfo:"获取验证码",
            vipForm:{
                name:"",
                code:"",
                mobile:""
            },
            // 
            isPrintPrev:false,
            endDay:0,//过期天数
            endTime:"",//到期时间
            showConfirmMask: false,//退出登录按钮

            launchFullBtn: true,//全屏控制按钮
            employeeInfo: {},//账号信息
            storeInfo: {},//店铺信息
            ordersId: '',//订单id

            // 更新订单数量
            timer:'',
            orderNum: 0,
            waitNum:0,
            leaseNum:0,
            weekStr: '', // 星期
            dateStr: '', // 年月日
            timeStr: '', // 时分秒
            intervalTimer: {}, // 时间定时器
            vipBoxBtn:false,//会员弹框
            qrCodeBtn:false,//添加会员
            
            rechargeBoxBtn:false,//会员充值

            rulesData:{},
            curSelectVipData:{},
            inputVipMoney:'',
            vipPayBtn:false,
            vipObj:{},
            payVipType : "CASH", // 会员支付方式
            payCode:'',
            showPayCodeBox: false, // 是否显示在线支付
            showOnLinePaySuccessMask: false, // 在线支付成功提示框
            showPayLoding: false, // 是否显示等待支付框
            inputVipCodeBtn: true,//输入会员
            vipNumber:"",
            curVipIdx:0,
            vipList:[],
            searchVipBtn: true, // 搜索会员接口控制
            payApiBtn: true, // 支付情况控制
            MorePayBtn:false,

            timeNum: true, // 支付等待时间
            payLoadTimer:'',

            printsBtn: false, // 打印勾选按钮
            showSetting: false, // 显示设置界面
            channelType: { // 结算方式
				// ALIPAY: '支付宝',
				// CASH: '现金',
				// WECHATPAY: '微信',
				// MEMBER : '会员支付',
                // WECHATPAY_CASH : '线下微信',
                // ALIPAY_CASH : '线下支付宝',
                "CASH": "现金",
                "ALIPAY": "支付宝",
                "WECHATPAY": "微信",
                "UNIONPAY": "银联",
                "pay.weixin.micropay":"微信刷卡",
                "pay.wechat.micropay":"微信刷卡",
                "pay.alipay.micropay":"支付宝刷卡",
                "pay.jdpay.micropay":"京东刷卡",
                "pay.qq.micropay":"QQ钱包刷卡",
                "pay.shiming.micropay":"会员卡",
                "pay.unionpay.micropay":"银联支付",
                "pay.bestpay.micropay":"翼支付",
                "pay.weixin.native":"微信扫码",
                "pay.wechat.native":"微信扫码",
                "pay.alipay.native":"支付宝扫码",
                "ALIPAY_CASH":"支付宝线下",
                "WECHATPAY_CASH":"微信线下",
                "COUPON":"优惠券",
                "MEMBER":"会员",
                "pay.wechat.jspay":"微信网页支付",
                "pay.alipay.jspay":"支付宝网页支付",

			},
            settingObj: {
                orderVoiceName: '', // 订单提示音
                autoPrint: 'ON', // 自动打印
                totalClassify: 'DETAILARRTYPE', // 总分类打印
                printId:'',//小票打印机id
                kitchIp:'',//厨房打印IP
                kitchPort:'9100',//厨房打印端口
                kitchPrintCount:2,//厨房默认打印份数
                pasterName: '', // 标签打印机名称
                isTagPrint:false,//是否允许标签打印
                printIdForTag:"",//标签打印机的硬件ID
                printIdForSale:"",//小票打印机的硬件ID
                payVoiceVolum:30,
                orderVoiceVolum:50,
                offlineVoiceVolum:100,
                // 
                isAutoPrintOrder:false,
                handlePrint:"ON",
                // 
                printRentOrder:"ON",
            },
            curVoiceName: 'voice_1.ogg', // 当前声音名称

            voice_text_index: '', // 到账声音
            isOnline: true, // 是否走银行通道

            stompClient: null, // stomp客户端对象
            stompClientNotice: null, // stomp客户端对象(语音服务)
            updatesTime: '', // 
            token: '',
            timerNotice:'',
            ipTimer:"",
            voiceTimer:"",
            noticeBtn:false,
            noticeUpdatesTime:'',//(语音服务)初试时间
            noticeWill:[],//(语音服务)将要播报的数组
            voice_text_notice:'',//(语音服务)文字
            noticeTotalElements:0,//(语音服务)总条
            noticeCurrentPage: 1, //(语音服务)翻页当前页
            noticeList:[],
            // 
            couponList:[],
            couponType: {
                "GET_ITEM_FREE": '商品抵用券',
                "REDUCE": "代金券"
            },
            loading:false,
            members:[],
            printsNum:1,
            deliveryEnabled:false,
            playingFlag:false,
        }
    },
    watch: {
        qrCodeBtn(val){
            if(!val){
                this.vipForm = {
                    name:"",
                    code:"",
                    mobile:""
                }
            }
        },
        vipNumber (val) {
            if ( !this.searchVipBtn || !val ) {
                return;
            }
            this.searchVipBtn = false;
            this.$http.get('members?storeId=' + this.storeInfo.storeId + '&q=' + val).then((res) => {
                this.vipList = res.data;
                if (this.vipList && this.vipList[0]) {
                    this.curSelectVipData = this.vipList[0];
                }
                this.searchVipBtn = true;
                setTimeout(()=>{
                    let that = this;
                    $('.vipCheckList li').hover( function () {
                        that.curVipIdx = $(this).index()-1;
                    }, function () {
                        that.curVipIdx = 0;
                    })
                },0)
            }).catch(()=>{
                this.searchVipBtn = true;
            })
        },
    },
    methods: {
        testQrcode(){
            const url = "https://example.com"; // 替换为你的内容
            const qrcode = new QRCode(document.getElementById('qrcode'), {
                text: url,
                width: 200,
                height: 200,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H // 高容错率
            });
            setTimeout(()=>{
                let array = [];
                const canvas = document.querySelector('#qrcode canvas');
                const imageData = canvas.getContext('2d').getImageData(0, 0, 200, 200);
                const bitmap = this.convertTo1Bit(imageData.data, 200, 200);
                const cmd = this.generateBitmapCommand(bitmap, 200, 200);
                array = array.concat([27,97,49]);//居中
                console.log(cmd)
                array =  array.concat(cmd);
                array = array.concat([27,100,2]);//空格走纸
                array = array.concat([27,100,2]);//空格走纸
                array = array.concat([27,105]);//切纸           
                print_((localStorage.getItem('printIdForSale')?localStorage.getItem('printIdForSale'):''),array);//小票打印
            },500);
        },
        // 使用Canvas处理图像
        convertTo1Bit(imageData, width, height) {
            const bitmap = [];
            for (let y = 0; y < height; y++) {
            let byte = 0,
                bits = 0;
            for (let x = 0; x < width; x++) {
                const idx = (y * width + x) * 4;
                const r = imageData[idx],
                g = imageData[idx + 1],
                b = imageData[idx + 2];
                const isBlack = r + g + b < 200; // 简单二值化
                byte |= (isBlack ? 1 : 0) << (7 - bits);
                bits++;
                if (bits === 8) {
                bitmap.push(byte);
                byte = 0;
                bits = 0;
                }
            }
            if (bits > 0) bitmap.push(byte); // 补足末尾字节
            }
            return bitmap;
        },
        generateBitmapCommand(bitmapData, width, height) {
            const bytesPerLine = Math.ceil(width / 8);
            const xL = bytesPerLine % 256;
            const xH = Math.floor(bytesPerLine / 256);
            const yL = height % 256;
            const yH = Math.floor(height / 256);

            // 指令格式: GS v 0 [xL xH yL yH] [位图数据]
            return [
            0x1d,
            0x76,
            0x30,
            0x00, // GS v 0
            xL,
            xH,
            yL,
            yH, // 宽度（字节数）和高度
            ...bitmapData, // 位图数据
            ];
        },
        generateEscStarCommand(bitmapData, width) {
            const bytesPerLine = Math.ceil(width / 8);
            return [
            0x1b,
            0x2a,
            0x21, // ESC * 33 (单密度位图)
            bytesPerLine % 256,
            bytesPerLine >> 8, // 每行字节数
            ...bitmapData,
            ];
        },
        // 
        testTagPrint(){
            let data = {
                tableNo:"测试",
                createTime:new Date().getTime(),
                notes:"测试备注",
            }
            let labelPrintData = [
                {
                    id:1,
                    productName:"测试商品",
                    salesPrice:0,
                    quantity:1
                }
            ]
            try {
                window.bridgeEx.openPrint(this.settingObj.printIdForTag);
            } catch (error) {
                console.log('error',error)
            }
            setTimeout(()=>{
                this.surePrintForTag(data,labelPrintData,this.settingObj.printIdForTag);
            },1000);
        },
        testPrint(){
            try {
                window.bridgeEx.openPrint(this.settingObj.printIdForSale);
            } catch (error) {
                console.log('error',error)
            }
            let curOrderData = {
                tableNo:"测试",
                code:"测试流水号",
                paymentTime:new Date().getTime(),
                creatorName:"打印测试",
                source:"EMPLOYEE",
                payments:[
                    {
                        channel:"CASH"   
                    }
                ],
                items:[
                    {
                        id:1,
                        productName:"测试商品",
                        salesPrice:0,
                        quantity:1,
                        labelEnabled:false,
                    }
                ],
                total:0,
                count:1,
                discount:0,
                amount:0,
                notes:"测试备注",
            }
            setTimeout(()=>{
                this.surePrint(curOrderData);
            },1000);
        },
        // 
        testAudio(type){
            try {
                $('.testAudio').remove();
                $('.index').append($('<audio style="display:none" controls="" class="testAudio" src="../../../static/voice/'+this.curVoiceName+'" id="audios"></audio>'));
                if(type == "order"){
                    if(this.audioDevice){
                        let deviceId = "";
                        this.allAudioOptions.forEach(it=>{
                            if(it.label == this.audioDevice){
                                deviceId = it.deviceId;
                            }
                        });
                        console.log("deviceId",deviceId);
                        $(".testAudio")[0].setSinkId(deviceId);
                    }
                    $(".testAudio")[0].play();
                }else{
                    if(this.audioDeviceForOffline){
                        let deviceId = "";
                        this.allAudioOptions.forEach(it=>{
                            if(it.label == this.audioDeviceForOffline){
                                deviceId = it.deviceId;
                            }
                        });
                        console.log("deviceId",deviceId);
                        $(".testAudio")[0].setSinkId(deviceId);
                    }
                    $(".testAudio")[0].play();
                }
                $(".testAudio").on("ended",function () {
                    this.remove();
                })
            } catch (error) {
                console.log(error);
            }
        },
        submitDsbt(){
            if(!this.couponCount){
                this.$message({
                    message: "请选择优惠券数量",
                    type: 'error'
                });
                return;
            }
            if(!this.nowSelVips || !Array.isArray(this.nowSelVips) || !this.nowSelVips.length){
                this.$message({
                    message: "请选择会员",
                    type: 'error'
                });
                return;
            }
            // let memeberIds = [];
            // this.nowSelVips.forEach(it=>{
            //     memeberIds.push(it);
            // })
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            this.$http({
                url:"distribute-coupon",
                method:"POST",
                data:{
                    couponId:this.nowSelCouponItem.id,
                    distributeType:"SINGLE",
                    memeberIds:this.nowSelVips,
                    qty:this.couponCount,
                    storeId:this.storeInfo.storeId
                }
            }).then(res=>{
                setTimeout(()=>{
                    this.canClick = true;
                },500);
                this.showDsbtCoupon = false;
                this.nowSelVips = [];
                this.nowSelCouponItem = null;
                this.couponCount = "";
                this.$message({
                    message: "派发成功",
                    type: 'success'
                });
            }).catch(err=>{
                setTimeout(()=>{
                    this.canClick = true;
                },500);
            })
        },
        // 
        remoteMethod(query){
            if(query != ""){
                this.loading = true;
                this.$http({
                    url:"members",
                    method:"GET",
                    params:{
                        storeId:this.storeInfo.storeId,
                        q:query
                    }
                }).then(res=>{
                    this.loading = false;
                    this.members = res.data;
                }).catch(err=>{
                    this.loading = false;
                })
            }
        },
        dsbtCoupon(it){
            this.nowSelCouponItem = it;
            this.showDsbtCoupon = true;
        },
        clearCoupon(){
            this.nowSelCouponItem = null;
        },
        toDsbtCoupon(it){
            if(this.nowSelCouponItem && it.id == this.nowSelCouponItem.id){
                this.clearCoupon();
                return;
            }
            this.nowSelCouponItem = it;
        },
        getCouponList(){
            let userName = sessionStorage.getItem("userName");
            this.$http({
                url:"coupon",
                method:"GET",
                params:{
                    storeId:this.storeInfo.storeId,
                    userName,
                    page:0,
                    size:1000
                }
            }).then(res=>{
                console.log(res);
                this.couponList = res.data.content;
            })
        },
        // 
        closeCouponBox(){
            this.showSendCouponBox = false;
        },
        openSendCouponBox(){
            // 
            this.getCouponList();
            // 
            this.vipBoxBtn = false;
            this.showSendCouponBox = true;
        },
        // 
        submitVip(){
            if(!String(this.vipForm.mobile).trim()){
                this.$message({
                    message: '请输入手机号',
                    type: 'error'
                });
                return;
            }
            // if(!String(this.vipForm.name).trim()){
            //     this.$message({
            //         message: '请输入姓名',
            //         type: 'error'
            //     });
            //     return;
            // }
            // if(!String(this.vipForm.code).trim()){
            //     this.$message({
            //         message: '请输入验证码',
            //         type: 'error'
            //     });
            //     return;
            // }
            this.$http({
                url:"add/members",
                method:"GET",
                params:{
                    ...this.vipForm,
                    storeId:this.storeInfo.storeId
                }
            }).then(res=>{
                this.qrCodeBtn = false;
                this.$message({
                    message: res.data,
                    type: 'success'
                });
            })
        },
        getCode(){
            if(!String(this.vipForm.mobile).trim()){
                this.$message({
                    message: '请输入手机号',
                    type: 'error'
                });
                return;
            }
            if (this.codeInfo != "获取验证码") {
                return;
            }
            this.$http
                .post(`${API_BASE_URL}v1/verify-code?mobile=${this.vipForm.mobile}&type=ACCOUNT`)
                .then((res) => {
                    clearInterval(this.timer);
                    let time = 60;
                    this.timer = setInterval(() => {
                        time--;
                        this.codeInfo = `${time}s`;
                        if (time <= 0) {
                            this.codeInfo = "获取验证码";
                            clearInterval(this.timer);
                        }
                    }, 1000);
            });
        },
        //挂单
        aNewOrder(){
            clearInterval(this.payLoadTimer);
            this.payApiBtn = true;
            this.showPayLoding = false;
            this.vipPayBtn = false;
            this.inputVipMoney = '';
        },
        //取消单
        deleteOrder( orderId ){
            clearInterval(this.payLoadTimer);
            this.payApiBtn = true;
            this.$http.delete('payments/'+orderId).then((res)=>{
                this.showPayLoding = false;
                this.vipPayBtn = false;
                this.inputVipMoney = '';
                // 传入index生成新订单
            });
        },
        addVipFn(item){
            this.curSelectVipData = item;
            this.curSelectVipData.curMoney = item.amount+item.bonus;//curMoney为当前会员展示的余额
            this.curSelectVipData.curMoney = this.curSelectVipData.curMoney.toFixed(2);
            this.inputVipCodeBtn =false;
            this.searchVipBtn = true;
        },
        // 打开在线支付框事件
        openPayCodeBox: function () {
            this.showPayCodeBox = true;
            this.payCode = '';
            setTimeout(()=>{
                $('#payCodeInput').focus();
            }, 0)
        },
        // 
        // 
        convertCurrency(num) {
      const chineseNum = {
          digits: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
          units: ['', '十', '百', '千'],
          bigUnits: ['', '万', '亿', '万亿']
      };

      function convertInteger(numStr) {
          if (numStr === '0') return '零';
          let result = '';
          let zeroCount = 0;
          const len = numStr.length;

          for (let i = 0; i < len; i++) {
              const digit = parseInt(numStr[i]);
              const pos = len - i - 1;
              const unitIndex = pos % 4;
              const bigUnitIndex = Math.floor(pos / 4);

              if (digit === 0) {
                  zeroCount++;
              } else {
                  if (zeroCount > 0) {
                      result += '零';
                      zeroCount = 0;
                  }
                  // 处理十位的特殊读法（例如：10读作"十"，110读作"一百一十"）
                  if (digit === 1 && unitIndex === 1 && i === 0) {
                      result += chineseNum.units[unitIndex];
                  } else {
                      result += chineseNum.digits[digit] + chineseNum.units[unitIndex];
                  }
              }

              // 添加大单位（万/亿）
              if (unitIndex === 0 && bigUnitIndex > 0) {
                  result += chineseNum.bigUnits[bigUnitIndex];
              }
          }

          return result.replace(/零+$/, '') || '零';
      }

      function convertDecimal(decimalStr) {
          return decimalStr.split('').map(c => chineseNum.digits[parseInt(c)]).join('');
      }

      // 主处理逻辑
      let numStr = typeof num === 'string' ? num : String(num);
      let isNegative = false;
      
      // 处理负数
      if (numStr.startsWith('-')) {
          isNegative = true;
          numStr = numStr.slice(1);
      }

      const [integerPart, decimalPart] = numStr.split('.');
      let result = convertInteger(integerPart || '0');

      // 处理小数部分
      if (decimalPart) {
          const isAllZero = decimalPart.split('').every(c => c === '0');
          if (!isAllZero) {
              result += '点' + convertDecimal(decimalPart);
          }
      }

      return (isNegative ? '负' : '') + result;
  },
        // convertCurrency(money) {
        //     //汉字的数字
        //     var cnNums = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        //     //基本单位
        //     var cnIntRadice = new Array('', '十', '百', '千');
        //     //对应整数部分扩展单位
        //     var cnIntUnits = new Array('', '万', '亿', '兆');
        //     //对应小数部分单位
        //     var cnDecUnits = new Array('', '', '毫', '厘');
        //     //整数金额时后面跟的字符
        //     var cnInteger = '';
        //     //整型完以后的单位
        //     var cnIntLast = '点';
        //     //最大处理的数字
        //     var maxNum = 999999999999999.9999;
        //     //金额整数部分
        //     var integerNum;
        //     //金额小数部分
        //     var decimalNum;
        //     //输出的中文金额字符串
        //     var chineseStr = '';
        //     //分离金额后用的数组，预定义
        //     var parts;
        //     if (money == '') { return ''; }
        //     money = parseFloat(money);
        //     if (money >= maxNum) {
        //         //超出最大处理数字
        //         return '';
        //     }
        //     if (money == 0) {
        //         chineseStr = cnNums[0] + cnIntLast + cnInteger;
        //         return chineseStr;
        //     }
        //     //转换为字符串
        //     money = money.toString();
        //     if (money.indexOf('.') == -1) {
        //         integerNum = money;
        //         decimalNum = '';
        //     } else {
        //         parts = money.split('.');
        //         integerNum = parts[0];
        //         decimalNum = parts[1].substr(0, 4);
        //     }
        //     //获取整型部分转换
        //     if (parseInt(integerNum, 10) > 0) {
        //         var zeroCount = 0;
        //         var IntLen = integerNum.length;
        //         for (var i = 0; i < IntLen; i++) {
        //             var n = integerNum.substr(i, 1);
        //             var p = IntLen - i - 1;
        //             var q = p / 4;
        //             var m = p % 4;
        //             if (n == '0') {
        //                 zeroCount++;
        //             } else {
        //                 if (zeroCount > 0) {
        //                     chineseStr += cnNums[0];
        //                 }
        //                 //归零
        //                 zeroCount = 0;
        //                 chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
        //             }
        //             if (m == 0 && zeroCount < 4) {
        //                 chineseStr += cnIntUnits[q];
        //             }
        //         }
        //         if(decimalNum!=''){
        //             chineseStr += cnIntLast;
        //         }
        //     }else{
        //         chineseStr+="零点";
        //     }
        //     //小数部分
        //     if (decimalNum != '') {
        //         var decLen = decimalNum.length;
        //         for (var i = 0; i < decLen; i++) {
        //             var n = decimalNum.substr(i, 1);
        //             if (n != '0') {
        //                 chineseStr += cnNums[Number(n)] + cnDecUnits[i];
        //             }else{
        //                 chineseStr+="零";
        //             }
        //         }
        //     }else{
        //         // chineseStr+="零零";
        //     }
        //     if (chineseStr == '') {
        //         chineseStr += cnNums[0] + cnIntLast + cnInteger;
        //     } else if (decimalNum == '') {
        //         chineseStr += cnInteger;
        //     }
        //     return chineseStr;
        // },
        generateMoneyNumVoice(numberStr){
            let voiceArr = [];
            if(numberStr){
            let numberArr = numberStr.split("");
            if(numberArr && Array.isArray(numberArr)){
                numberArr.forEach(it=>{
                voiceArr.push(`<audio style="display:none" id='paySucVoice' class="playRate" src='../../../static/voice/cgdz/${it}.mov'></audio>`);
                })
            }
            }
            return voiceArr;
        },
        payVoice(type,amount){
            let getAmount = Number(amount).toFixed(2);
            let cgdz = `<audio style="display:none" id='paySucVoice' src='../../../static/voice/cgdz/cgdz.mov'></audio>`;
            let yuan = `<audio style="display:none" id='paySucVoice' src='../../../static/voice/cgdz/yuan.mov'></audio>`;
            let errorVoice = `<audio style="display:none" id='paySucVoice' src='../../../static/voice/cgdz/zfsb.mp3'></audio>`;
            console.log(this.convertCurrency(Number(getAmount)));
            let moneyAudios = [];
            try {
                moneyAudios = this.generateMoneyNumVoice(this.convertCurrency(Number(getAmount)));
            } catch (error) {
                console.log(error)      
            }
            let audios = [cgdz,...moneyAudios,yuan];
            if(type == "error"){
                audios = [errorVoice];
            }
            if(audios && Array.isArray(audios) && audios.length){
                let audioIndex = 0;
                function playAudio(audioIndex){
                    if(audioIndex < audios.length){
                        $("#cashier").append(audios[audioIndex]);
                        console.log("正在播放"+audioIndex);
                        // 
                        let audioDevice = "";
                        audioDevice = localStorage.getItem("audioDevice");
                        try {
                            if(audioDevice){
                                console.log("paySucVoice",$("#paySucVoice")[0]);
                                console.log(`pay audio is being output on ${audioDevice}`);
                                $("#paySucVoice")[0].setSinkId(audioDevice);
                            }
                        } catch (error) {
                            console.log("error",error);
                        }
                        $("#paySucVoice")[0].play();
                        // 
                        $("#paySucVoice").on("playing",function () {
                        try {
                            if($(this).hasClass("playRate")){
                            // $(this)[0].playbackRate = 1;
                            }
                        } catch (error) {
                            console.log("error",error);
                        }
                        })
                        $("#paySucVoice").on("ended",function () {
                            this.remove();
                            playAudio(audioIndex+1);
                        })
                    }else{
                        console.log("播放完毕");
                        audios = [];
                        $("#paySucVoice").remove();
                    }
                }
                playAudio(audioIndex);
                setTimeout(() => {
                    $("#paySucVoice").remove();
                }, 15000);
                return;
            }
        },
        //会员充值
        vipPayFn(){
            if ( !this.payCode && this.payVipType == 'PAYCARD'  ) {
                this.$message({
                    message: '请输入收款码',
                    customClass: 'error'
                })
                return;
            }

            if ( !this.payApiBtn ) {
                return;
            }
            this.payApiBtn = false;
            this.showPayCodeBox = false;
            this.showPayLoding = true;

            this.$http.put('payments/' + this.$uuid(), {
                "orderId": this.vipObj.ordersId,
                "channel": this.payVipType,
                "amount":  this.vipObj.amount,
                "authCode": this.payCode,
            }).then((res)=>{
                this.payCode = '';
                if ( res.status === 202 && this.payVipType == 'PAYCARD' ) {
                    let overTimeNum = 0;
                    let curOrderId = this.vipObj.ordersId;

                    this.payLoadTimer = setInterval(()=>{
                        overTimeNum += 2;
                        let that = this;
                        if ( overTimeNum >= 180 ) { // 超过180秒，取消订单
                            clearInterval(this.payLoadTimer);
                            this.payApiBtn = true;
                            this.showPayLoding = false;
                            this.$message({
                                message: '支付超时，当前订单已取消！',
                                customClass: 'error'
                            })
                            this.deleteOrder( curOrderId );
                            return;
                        }
                        this.payLoad(this.vipObj.ordersId, function () {
                            clearInterval(that.payLoadTimer);
                            that.$http.get('members?storeId='+that.storeInfo.storeId+'&q='+encodeURI(that.curSelectVipData.code)).then((res)=>{
                                that.curSelectVipData = res.data[0];
                                that.curSelectVipData.curMoney = res.data[0].amount+res.data[0].bonus;//curMoney为当前会员展示的余额
                                that.curSelectVipData.curMoney = that.curSelectVipData.curMoney.toFixed(2);
                                sessionStorage.setItem('curSelectVipData', JSON.stringify(that.curSelectVipData));
                            })
                            that.$message({
                                message: '充值成功',
                                customClass: 'success'
                            });
                            that.vipPayBtn = false;
                            that.showPayLoding = false;
                            that.rechargeBoxBtn = false;
                            that.showOnLinePaySuccessMask = true;
                            that.inputVipMoney = '';
                            that.MorePayBtn = false
                            setTimeout(()=>{
                                that.payApiBtn = true;
                            }, 300)
                            that.payVoice('',that.vipObj.amount);
							// var iframe = "<iframe id='iframes' height='0' width='0' src='"+API_BASE_URL+"v1/pos/speech?tex=成功到账"+that.vipObj.amount+"元&vol=9&per=0&spd=5&pit=5' frameborder='0'></iframe>";
	            //             $('#index').append(iframe)
	            //             setTimeout(()=>{
	            //                 $("#iframes").remove();
	            //             },8000)
//                          that.voice_text_index = '成功到账'+that.vipObj.amount+'元';
//                          setTimeout(()=>{
//                              $('#speech_voice_index').speech({
//                                  "speech": false,
//                                  "speed": 3,
//                              });
//                          })
                        })
                    }, 2000);
                } else {
                    this.$http.get('members?storeId='+this.storeInfo.storeId+'&q='+encodeURI(this.curSelectVipData.code)).then((res)=>{
                        this.curSelectVipData = res.data[0];
                        this.curSelectVipData.curMoney = res.data[0].amount+res.data[0].bonus;//curMoney为当前会员展示的余额
                        this.curSelectVipData.curMoney = this.curSelectVipData.curMoney.toFixed(2);
                        sessionStorage.setItem('curSelectVipData', JSON.stringify(this.curSelectVipData));
                    })
                    this.$message({
                        message: '充值成功',
                        customClass: 'success'
                    });
                    this.vipPayBtn = false;
                    this.showPayLoding = false;
                    this.rechargeBoxBtn = false;

                    if ( this.payVipType == 'PAYCARD' ) {
                        this.showOnLinePaySuccessMask = true;
                        this.payVoice('',this.vipObj.amount);
                        // var iframe = "<iframe id='iframes' height='0' width='0' src='"+API_BASE_URL+"v1/pos/speech?tex=成功到账"+this.vipObj.amount+"元&vol=9&per=0&spd=5&pit=5' frameborder='0'></iframe>";
                        // $('#index').append(iframe)
                        // setTimeout(()=>{
                        //     $("#iframes").remove();
                        // },8000)
//                      this.voice_text_index = '成功到账'+this.vipObj.amount+'元';
//                      setTimeout(()=>{
//                          $('#speech_voice_index').speech({
//                              "speech": false,
//                              "speed": 3,
//                          });
//                      })
                    }

                    this.inputVipMoney = '';
                    this.MorePayBtn = false
                    setTimeout(()=>{
                        this.payApiBtn = true;
                        this.showPayLoding = false;
                    }, 300)
                }
            }).catch(()=>{
                this.payApiBtn = true;
                this.showPayLoding = false;
            })
        },
        //会员充值
        rechargeFn(){
            this.vipBoxBtn = false;
            this.rechargeBoxBtn =true;
            this.inputVipCodeBtn = true;
            this.vipPayBtn = false;
            this.vipList = [];
            this.vipNumber = '';
            // 获取充送规则
            this.$http.get('charge-rules?storeId='+this.storeInfo.storeId).then((res)=>{
                this.rulesData = res.data;
            })
        },
        // 等待支付轮训接口
        payLoad: function ( orderId, fn ) {
            this.$http.get(API_BASE_URL+'v1/pay/micropay/query?orderId='+orderId).then((res)=>{
                if ( res.status === 200 ) {
                    fn();
                }
            }).catch(( err )=>{
                this.payApiBtn = true;
                this.showPayLoding = false;
                clearInterval(this.payLoadTimer);
            })
        },
        choiceRules(item){
            if( item ){
                this.inputVipMoney = '';//防止用户填了自定义充值，但结果选了冲送规则。
            }else {
                if(!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.inputVipMoney)|| this.inputVipMoney == 0){
                    this.$message({
                        message: '充值金额输入有误',
                        customClass: 'error'
                    });
                    return;
                }
            }
            this.payVipType = 'CASH';
            let userName = sessionStorage.getItem("userName");
            let sendBody = {
                "storeId": this.storeInfo.storeId,
                "memberId": this.curSelectVipData.id,
                "amount": parseFloat(this.inputVipMoney?this.inputVipMoney:item.depositAmount),
                "chargeRuleId": this.inputVipMoney?'':item.id,
                "type":"POS",
                userName
            }
            this.$http.put('member-charges/'+this.$uuid(),sendBody).then((res)=>{
                this.vipObj = item?item:{};
                this.$set(this.vipObj, 'code', res.data.code);
                this.$set(this.vipObj, 'ordersId', res.data.id);
                this.$set(this.vipObj, 'amount', res.data.amount);
            })
            this.vipPayBtn = true;
        },
        //添加会员
        addVip(){
            this.vipBoxBtn = false;
            this.qrCodeBtn=true;
            setTimeout(
                ()=>{
                    $('#qrcode')[0].innerHTML='';
                    this.$http.get(API_BASE_URL+'v1/clerk/referral-code?storeId='+this.storeInfo.storeId).then((res)=>{
                        let qrcode = new QRCode("qrcode", {
                            text: res.data,
                            colorDark : "#000000",
                            colorLight : "#ffffff",
                            correctLevel : QRCode.CorrectLevel.H
                        });
                    }).catch((res)=>{
                    })

                },0
            )
        },
        logout(){
            this.$http.post(API_BASE_URL+'logout', {}).then((res)=>{
                console.log("9");
                localStorage.removeItem("orders");
                this.$router.push({path: '/login'});
            }).catch((err)=>{

            });
            //退出登录
            // this.$router.push({path: '/login'});
        },
        getNewNum(number){
            //number 为待处理订单页面过来的订单数量
            this.orderNum = number;
        },
        // 设置
        setting:async function () {
            try {
                const printDevices = await window.getUsbPrintDeviceList();
                // vid_0471&pid_0055|vid_0483&pid_070b
                if(printDevices){
                    if(printDevices.split("|") && Array.isArray(printDevices.split("|")) && printDevices.split("|").length){
                        this.printDevices = printDevices.split("|");
                    }
                }
                console.log("getUsbPrintDeviceListPre",printDevices);
                console.log("getUsbPrintDeviceListAfter",this.printDevices);
            } catch (error) {
                console.log(error)
            }
            try {
                const version = await window.onGetVer();
                console.log("version",version);
                if(version){
                    let tempVersionArr = version.split(".");
                    tempVersionArr = tempVersionArr.join("");
                    console.log("Number(tempVersionArr)",Number(tempVersionArr))
                    if(Number(tempVersionArr) >= 1100){
                        this.handlePrint = false;
                    }
                }
            } catch (error) {
                console.log("error",error)
            }
            this.showSetting = true;
            this.settingObj = {
                orderVoiceName: localStorage.getItem('orderVoiceName'), // 订单提示音
                autoPrint: JSON.parse(localStorage.getItem('autoPrint')).autoPrint, // 自动打印
                totalClassify: localStorage.getItem('totalClassify'), // 总分类打印
                pasterName: localStorage.getItem('pasterName')?localStorage.getItem('pasterName'):'', // 总分类打印
                printId: localStorage.getItem('printId')?localStorage.getItem('printId'):'', // 小票打印
                kitchIp: localStorage.getItem('kitchIp')?localStorage.getItem('kitchIp'):'', // 厨房打印Ip
                kitchPort: localStorage.getItem('kitchPort')?localStorage.getItem('kitchPort'):'', // 厨房打印端口
                kitchPrintCount: localStorage.getItem('kitchPrintCount')?localStorage.getItem('kitchPrintCount'):2, // 厨房打印端口
                isTagPrint:JSON.parse(localStorage.getItem('isTagPrint'))?localStorage.getItem('isTagPrint'):false, // 是否允许厨房打印
                printIdForSale:localStorage.getItem('printIdForSale')?localStorage.getItem('printIdForSale'):'',//小票打印机硬件ID
                printIdForTag:localStorage.getItem('printIdForTag')?localStorage.getItem('printIdForTag'):'',//标签打印机硬件ID
                // 
                payVoiceVolum:localStorage.getItem('payVoiceVolum') ? Number(localStorage.getItem('payVoiceVolum')) : 100,
                orderVoiceVolum:localStorage.getItem('orderVoiceVolum') ? Number(localStorage.getItem('orderVoiceVolum')) : 100,
                offlineVoiceVolum:localStorage.getItem('offlineVoiceVolum') ? Number(localStorage.getItem('offlineVoiceVolum')) : 100,
                // 
                isAutoPrintOrder:JSON.parse(localStorage.getItem('isAutoPrintOrder'))?localStorage.getItem('isAutoPrintOrder'):false, // 是否允许厨房打印
                // handlePrint:localStorage.getItem('handlePrint')==""?"ON":localStorage.getItem('handlePrint')
                // 
                printRentOrder:localStorage.getItem('printRentOrder') ? localStorage.getItem('printRentOrder') : "ON", // 是否允许厨房打印
            }
            let audioDevice = localStorage.getItem("audioDevice");
            if(audioDevice){
                this.audioDevice = audioDevice;
            }
            let audioDeviceForOffline = localStorage.getItem("audioDeviceForOffline");
            if(audioDeviceForOffline){
                this.audioDeviceForOffline = audioDeviceForOffline;
            }
        },
        // 保存设置
        saveSetting: function () {
            this.settingObj.pasterName = this.settingObj.pasterName.replace(/(^\s*)|(\s*$)/g,''); // 去掉前后空格
            this.settingObj.printId = this.settingObj.printId.replace(/(^\s*)|(\s*$)/g,''); // 去掉前后空格
            this.settingObj.kitchIp = this.settingObj.kitchIp.replace(/(^\s*)|(\s*$)/g,''); // 去掉前后空格
            this.settingObj.kitchPort = this.settingObj.kitchPort.replace(/(^\s*)|(\s*$)/g,''); // 去掉前后空格
            this.settingObj.kitchPrintCount = this.settingObj.kitchPrintCount.replace(/(^\s*)|(\s*$)/g,''); // 去掉前后空格
            this.settingObj.isTagPrint = this.settingObj.isTagPrint;
            this.settingObj.isAutoPrintOrder = this.settingObj.isAutoPrintOrder;
            
            // 
            let printIdForSale = this.settingObj.printIdForSale.replace(/(^\s*)|(\s*$)/g,'');
            let printIdForTag = this.settingObj.printIdForTag.replace(/(^\s*)|(\s*$)/g,'');

            this.settingObj.printIdForSale = printIdForSale.toLocaleLowerCase(); // 
            this.settingObj.printIdForTag = printIdForTag.toLocaleLowerCase(); // 
            // 

            // 厨房打印最多两张
            if(!/^[0-9]$/.test(this.settingObj.kitchPrintCount)){
                this.$message({
                    message: '厨房打印份数输入有误',
                    customClass: 'error'
                });
                return;
            }
            if(parseInt(this.settingObj.kitchPrintCount) > 2){
                this.$message({
                    message: '厨房打印最多两张',
                    customClass: 'error'
                });
                return;
            }
            if(parseInt(this.settingObj.kitchPrintCount) < 0){
                this.$message({
                    message: '厨房打印份数输入有误',
                    customClass: 'error'
                });
                return;
            }
            // 
            if(this.audioDevice){
                localStorage.setItem("audioDevice",this.audioDevice);
            }
            // 
            // 
            if(this.audioDeviceForOffline){
                localStorage.setItem("audioDeviceForOffline",this.audioDeviceForOffline);
            }
            //
            this.showSetting = false;
            // 
            let autoPrints = JSON.parse(localStorage.getItem('autoPrint'));
            autoPrints.autoPrint = this.settingObj.autoPrint;
            this.$http({
                url:"store-print-config",
                method:"POST",
                data:{
                    storeId:this.storeInfo.storeId,
                    receiptAuto:JSON.stringify(autoPrints),
                    receiptType:this.settingObj.totalClassify,
                    allowLabel:this.settingObj.isTagPrint,
                    labelPrintId:this.settingObj.printIdForTag,
                    receiptPrintId:this.settingObj.printIdForSale,
                    kitchenIp:this.settingObj.kitchIp,
                    kitchenPort:this.settingObj.kitchPort,
                    kitchenAmount:this.settingObj.kitchPrintCount,
                    audio:this.settingObj.orderVoiceName,
                    // 
                    paidVolume:this.settingObj.payVoiceVolum,
                    orderVolume:this.settingObj.orderVoiceVolum,
                    shutdownVolume:this.settingObj.offlineVoiceVolum,
                }
            }).then(res=>{
                // console.log("res",res);
                this.$message({
                    message: '保存成功',
                    customClass: 'success'
                })
            })
            // 
            
            console.log("this.settingObj",this.settingObj);

            localStorage.setItem('orderVoiceName', this.settingObj.orderVoiceName);
            localStorage.setItem('autoPrint', JSON.stringify(autoPrints));
            localStorage.setItem('totalClassify', this.settingObj.totalClassify);
            localStorage.setItem('pasterName', this.settingObj.pasterName);
            localStorage.setItem('printId', this.settingObj.printId);
            localStorage.setItem('kitchIp', this.settingObj.kitchIp);
            localStorage.setItem('kitchPort', this.settingObj.kitchPort);
            localStorage.setItem('kitchPrintCount', this.settingObj.kitchPrintCount);
            localStorage.setItem('isTagPrint', this.settingObj.isTagPrint);
            // 
            localStorage.setItem('isAutoPrintOrder', this.settingObj.isAutoPrintOrder);
            // 
            localStorage.setItem('printIdForSale', this.settingObj.printIdForSale);
            localStorage.setItem('printIdForTag', this.settingObj.printIdForTag);
            // 
            localStorage.setItem('payVoiceVolum', this.settingObj.payVoiceVolum);
            localStorage.setItem('orderVoiceVolum', this.settingObj.orderVoiceVolum);
            localStorage.setItem('offlineVoiceVolum', this.settingObj.offlineVoiceVolum);
            localStorage.setItem('handlePrint', this.settingObj.handlePrint);
            // 
            try {
                localStorage.setItem('printRentOrder', this.settingObj.printRentOrder);
            } catch (error) {
                console.log("error",error)
            }

            this.curVoiceName = this.settingObj.orderVoiceName;
            if ( this.settingObj.autoPrint == 'ON' ) {
                this.printsBtn = true;
            } else {
                this.printsBtn = false;
            }
        },
        // 选择声音
        selVoice: function () {
            $('.audio').remove();
            $('.index').append($('<audio style="display:none" controls="" class="audio" src="../../../static/voice/'+this.settingObj.orderVoiceName+'" autoplay="" id="audios"></audio>')); 
        },
        promisePrint(orderId){
            return new Promise((resolve,reject)=>{
                this.$http({
                    url:`/orders/${orderId}`,
                    method:"GET",
                    params:{}
                }).then(orderRes=>{
                    console.log("res",orderRes);
                    let curOrderData = orderRes.data;
                    
                    if(orderRes.data.payments && Array.isArray(orderRes.data.payments) && orderRes.data.payments.length){
                        let channel = orderRes.data.payments[0].channel;
                        if(channel!="CASH"){
                            // 
                            let doFinishFlag = false;
                            try {
                                for(var k = 0;k<curOrderData.items.length;k++){
                                    if(curOrderData.items[k].productTypeId&&curOrderData.items[k].productTypeId!='1'){
                                        doFinishFlag = true;
                                    }
                                }
                            } catch (error) {
                                console.log(error)
                            }
                            if(!doFinishFlag){
                                console.log("无需自动打印")
                                resolve();
                                return;
                            }
                            // 
                            this.$http.post('orders/'+orderId+'/finish').then((res)=>{
                                try {
                                    for(var k = 0;k<curOrderData.items.length;k++){
                                        if(curOrderData.items[k].productTypeId&&curOrderData.items[k].productTypeId!='1'){
                                            this.isCostPrintBtn = true;
                                        }
                                    }
                                    //控制是否打印 
                                    if(this.isCostPrintBtn){
                                        this.isCostPrintBtn = false;
                                        this.surePrint(curOrderData);
                                    }
                                    emitter.emit("refreshOrderList",{});
                                    this.sureKitchenPrint(curOrderData);//初始化打印配置
                                    setTimeout(()=>{
                                        this.canPrint = true;
                                    },1999)
                                } catch (error) {
                                    console.log(error);
                                }
                                resolve();
                            }).catch(()=>{
                                this.canPrint = true;
                                reject();
                            })
                        }else{
                            resolve();
                        }
                    }
                }).catch(err=>{
                    reject();
                });
            })
            
        },
        getOrderDetail(orderId){
            console.log("orderId,orderId",orderId)
            setTimeout(async ()=>{
                await this.promisePrint(orderId)
                // this.toPrintArr = [...this.toPrintArr,orderId];
                // // if(!this.canPrint){
                // //     return;
                // // }
                // // this.canPrint = false;
                // console.log("this.toPrintArr",this.toPrintArr)
                // if(this.toPrintArr && Array.isArray(this.toPrintArr) && this.toPrintArr.length){
                //     let pAll = [];
                //     let obj = {};
                //     this.toPrintArr.forEach((it,ind)=>{
                //         obj[it]=true;
                //         // 
                //     });
                //     for(let k in obj){
                //         pAll.push(this.promisePrint(k));
                //     }
                //     let res = await Promise.all(pAll);
                //     that.printCount = 0;
                //     this.toPrintArr = [];
                //     console.log("pRes",res);
                // }
            },1000)
        },
        // 
        surePrint(curOrderData){
            if ( localStorage.getItem('autoPrint')&&JSON.parse(localStorage.getItem('autoPrint')).watingOrder) {
                this.printsNum = JSON.parse(localStorage.getItem('autoPrint')).watingOrder;
            }
            if ( localStorage.getItem('autoPrint')) {
                let  autoPrints = JSON.parse(localStorage.getItem('autoPrint'));
                autoPrints.watingOrder = this.printsNum;
                localStorage.setItem('autoPrint', JSON.stringify(autoPrints));
            };
            console.log("自动打印小票start");
             //销售小票
            var array =[];
            array = array.concat([28,38]);//打印汉字
            array = array.concat([29,33,17]);//汉字倍宽高
            // array = array.concat([27,33,8]);//加粗
            array = array.concat([27,97,49]);//居中
            array = array.concat(gbk('欢迎光临'+this.storeName));
            array = array.concat([10]);//换行
            array = array.concat([27,97,48]);//左
            array = array.concat([29,33,0]);//取消汉字倍宽高
            array = array.concat(gbk('座位号:：'));
            array = array.concat([29,33,17]);
            if(curOrderData.tableNo != null){
                array = array.concat(gbk(curOrderData.tableNo));
            }
            array = array.concat([29,33,0]);
            array = array.concat([10]);//换行
            array = array.concat([29,33,8]);
            array = array.concat(gbk('流水号:：'+curOrderData.code));
            array = array.concat([10]);//换行
            array = array.concat([27,33,0]);//取消加粗
            array = array.concat(gbk('创建时间:：'+new Date(curOrderData.paymentTime).Format('yyyy/MM/dd-hh:mm')));
            array = array.concat([10]);//换行
            array = array.concat(gbk('打印时间:：'+new Date().Format('yyyy/MM/dd-hh:mm')));
            array = array.concat([10]);//换行
            array = array.concat(gbk('创建人:：'+curOrderData.creatorName));
            array = array.concat([10]);//换行
            if(curOrderData.source != "EMPLOYEE" && this.deliveryEnabled){
                array = array.concat(gbk('派送人员:：'+curOrderData.creatorName));
                array = array.concat([10]);//换行
            }
            array = array.concat(gbk('支付方式:：'+(curOrderData.payments[0]?this.channelType[curOrderData.payments[0].channel]:"-")));
            array = array.concat([27,100,2]);//空格走纸
            // array = array.concat([27,33,8]);//加
            for(var i=0;i<curOrderData.items.length;i++){
                if(curOrderData.items[i].id) {
                    array = array.concat(gbk('商品:：'+curOrderData.items[i].productName));
                    array = array.concat([10]);//换行
                    // 
                    if(curOrderData.items[i].specs && Array.isArray(curOrderData.items[i].specs) && curOrderData.items[i].specs.length){
                        let specs = curOrderData.items[i].specs.join("/");
                        array = array.concat(gbk('规格:：'+specs));
                        array = array.concat([10]);//换行  
                    }
                    // 
                    array = array.concat(gbk('数量:：'+curOrderData.items[i].quantity));
                    array = array.concat([10]);//换行
                    array = array.concat(gbk('单价:：'+curOrderData.items[i].salesPrice/curOrderData.items[i].quantity));
                    
                    if(curOrderData.items[i].masterItemDtos && Array.isArray(curOrderData.items[i].masterItemDtos) && curOrderData.items[i].masterItemDtos.length){
                        array = array.concat([10]);//换行
                        curOrderData.items[i].masterItemDtos.forEach(it=>{
                            array = array.concat(gbk('---配品:：'+it.productName));
                            array = array.concat([10]);//换行
                            array = array.concat(gbk('---数量:：'+it.quantity));
                            array = array.concat([10]);//换行
                            array = array.concat(gbk('---单价:：'+it.salesPrice/it.quantity));
                            array = array.concat([27,100,2]);//空格走纸
                            array = array.concat([10]);//换行 
                        })
                    }else{
                        array = array.concat([27,100,2]);//空格走纸
                        array = array.concat([10]);//换行
                    }
                }
            }
            array = array.concat(gbk('合计:：'+curOrderData.total));
            array = array.concat([10]);//换行 
            array = array.concat(gbk('总数:：'+curOrderData.count));
            array = array.concat([10]);//换行 
            array = array.concat(gbk('优惠:：'+curOrderData.discount));
            array = array.concat([10]);//换行 
            array = array.concat(gbk('应付:：'+curOrderData.amount));
            array = array.concat([10]);//换行 
            if(curOrderData.notes != null){
                array = array.concat(gbk('备注:：'+curOrderData.notes));
            }else{
                array = array.concat(gbk('备注:：'));
            }
            
            array = array.concat([10]);//换行
            array = array.concat([27,100,2]);//空格走纸
            array = array.concat([27,100,2]);//空格走纸

             //切纸
            // array = array.concat([10]);//换行 
            // array = array.concat([10]);//换行     
            // array = array.concat([27,100,2]);//空格走纸
            // array = array.concat([27,100,2]);//空格走纸    
            array = array.concat([27,105]);//切纸           
            array = array.concat([10]);//换行 
            //切纸结束
            
            //多份打印
            var arrays=[];
            for(var i = 0 ;i<this.printsNum;i++){
                  arrays = arrays.concat(array)
            }
            
            console.log("自动打印小票end",arrays);
            print_((localStorage.getItem('printIdForSale')?localStorage.getItem('printIdForSale'):''),arrays);//小票打印

            // 标签打印
            console.log(curOrderData)
            let newData = [];
            for(let j=0;j<curOrderData.items.length;j++){
                if(curOrderData.items[j].labelEnabled){
                    newData.push(curOrderData.items[j]);
                }
            }
            let labelPrintData = [];
            for(let i=0;i<newData.length;i++){
                if(newData[i].quantity==1){
                    labelPrintData.push(newData[i]);
                }else{
                    for(let y=0;y<newData[i].quantity;y++){
                        labelPrintData.push(newData[i]);
                    }
                }
            }
            if(JSON.parse(localStorage.getItem('isTagPrint'))&&(localStorage.getItem('printIdForTag')!="")){
                this.surePrintForTag(curOrderData,labelPrintData);
            }
            // 
           
        },
        sureKitchenPrint(curOrderData){
            let newkitchenPrintArr=[],kitchenPrintArr=[],IskitchenPrint=false;

            let printArr = {};

            let hasOtherPrint = false;
            console.log("厨房打印start")

            for(var i=0;i<curOrderData.items.length;i++){
                if(curOrderData.items[i].id) {
                    if(curOrderData.items[i].kitchenPrintEnabled){
                        // 
                        if(curOrderData.items[i].ipAddress){
                            hasOtherPrint = true;
                            if(!printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port]){

                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port] = {};
                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].printStr = [];
                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].items = [];

                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].items.push(curOrderData.items[i]);

                                let kitchenPrintArr=[];
                                kitchenPrintArr = kitchenPrintArr.concat([27,66,9,1]);//蜂鸣提醒
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                                if(curOrderData.tableNo != null){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'+curOrderData.tableNo));
                                }else{
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'));
                                }
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,0]);//取消汉字倍宽高
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('下单人:：'+curOrderData.creatorName));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                // 
                                if(curOrderData.source != "EMPLOYEE" && this.deliveryEnabled){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('派送人员:：'+curOrderData.creatorName));
                                    kitchenPrintArr = kitchenPrintArr.concat([10]);
                                }
                                // 
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('订单号:：'+curOrderData.code));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('下单时间:：'+new Date(curOrderData.createTime).Format('yyyy/MM/dd-hh:mm')));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('打印时间:：'+new Date().Format('yyyy/MM/dd-hh:mm')));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                                kitchenPrintArr = kitchenPrintArr.concat(gbk(curOrderData.items[i].productName));
                                // 
                                if(curOrderData.items[i].specs && Array.isArray(curOrderData.items[i].specs) && curOrderData.items[i].specs.length){
                                    let specs = curOrderData.items[i].specs.join("/");
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk("("+specs+")"));
                                }
                                //
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('('+curOrderData.items[i].quantity+')份'));
                                // kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//要打印的商品
                                kitchenPrintArr = kitchenPrintArr.concat([10]);//换行 
                                // 
                                if(curOrderData.items[i].masterItemDtos && Array.isArray(curOrderData.items[i].masterItemDtos) && curOrderData.items[i].masterItemDtos.length){
                                    curOrderData.items[i].masterItemDtos.forEach(it=>{
                                        if(it.kitchenPrintEnabled){
                                            kitchenPrintArr = kitchenPrintArr.concat(gbk('---配品:：'+it.productName));
                                            kitchenPrintArr = kitchenPrintArr.concat([10]);//换行
                                            kitchenPrintArr = kitchenPrintArr.concat(gbk('---数量:：'+it.quantity));
                                            kitchenPrintArr = kitchenPrintArr.concat([10]);//换行                    
                                            // kitchenPrintArr = kitchenPrintArr.concat(gbk('---单价:：'+(it.salesPrice/it.quantity).toFixed(2)));
                                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                        }
                                    })
                                }
                                // 
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,17]);//汉字倍宽高
                                if(curOrderData.notes != null){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'+curOrderData.notes));
                                }else{
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'));
                                }
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([29,86,0]);//切纸


                                if(parseInt(localStorage.getItem('kitchPrintCount'))===2){
                                    kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//默认两份
                                }else if(parseInt(localStorage.getItem('kitchPrintCount'))===0){
                                    kitchenPrintArr = [];
                                }
                                // kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//默认两份
                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].printStr = kitchenPrintArr;
                            }else{

                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].items.push(curOrderData.items[i]);

                                let kitchenPrintArr=[];
                                kitchenPrintArr = kitchenPrintArr.concat([27,66,9,1]);//蜂鸣提醒
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                                if(curOrderData.tableNo != null){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'+curOrderData.tableNo));
                                }else{
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'));
                                }
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,0]);//取消汉字倍宽高
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('下单人:：'+curOrderData.creatorName));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                // 
                                if(curOrderData.source != "EMPLOYEE" && this.deliveryEnabled){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('派送人员:：'+curOrderData.creatorName));
                                    kitchenPrintArr = kitchenPrintArr.concat([10]);
                                }
                                // 
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('订单号:：'+curOrderData.code));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('下单时间:：'+new Date(curOrderData.createTime).Format('yyyy/MM/dd-hh:mm')));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('打印时间:：'+new Date().Format('yyyy/MM/dd-hh:mm')));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                                kitchenPrintArr = kitchenPrintArr.concat(gbk(curOrderData.items[i].productName));
                                // 
                                if(curOrderData.items[i].specs && Array.isArray(curOrderData.items[i].specs) && curOrderData.items[i].specs.length){
                                    let specs = curOrderData.items[i].specs.join("/");
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk("("+specs+")"));
                                }
                                //
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('('+curOrderData.items[i].quantity+')份'));
                                // kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//要打印的商品
                                kitchenPrintArr = kitchenPrintArr.concat([10]);//换行 
                                // 
                                if(curOrderData.items[i].masterItemDtos && Array.isArray(curOrderData.items[i].masterItemDtos) && curOrderData.items[i].masterItemDtos.length){
                                    curOrderData.items[i].masterItemDtos.forEach(it=>{
                                        if(it.kitchenPrintEnabled){
                                            kitchenPrintArr = kitchenPrintArr.concat(gbk('---配品:：'+it.productName));
                                            kitchenPrintArr = kitchenPrintArr.concat([10]);//换行
                                            kitchenPrintArr = kitchenPrintArr.concat(gbk('---数量:：'+it.quantity));
                                            kitchenPrintArr = kitchenPrintArr.concat([10]);//换行                    
                                            // kitchenPrintArr = kitchenPrintArr.concat(gbk('---单价:：'+(it.salesPrice/it.quantity).toFixed(2)));
                                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                        }
                                    })
                                }
                                // 
                                kitchenPrintArr = kitchenPrintArr.concat([29,33,17]);//汉字倍宽高
                                if(curOrderData.notes != null){
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'+curOrderData.notes));
                                }else{
                                    kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'));
                                }
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                kitchenPrintArr = kitchenPrintArr.concat([29,86,0]);//切纸


                                if(parseInt(localStorage.getItem('kitchPrintCount'))===2){
                                    kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//默认两份
                                }else if(parseInt(localStorage.getItem('kitchPrintCount'))===0){
                                    kitchenPrintArr = [];
                                }

                                let arr = printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].printStr;

                                for(let k=0;k<kitchenPrintArr.length;k++){
                                    arr.push(kitchenPrintArr[k]);
                                }

                                // console.log(arr)
                                printArr[curOrderData.items[i].ipAddress+"_"+curOrderData.items[i].port].printStr = arr;

                            }
                        }else{
                            IskitchenPrint = true;

                            kitchenPrintArr=[];
                            kitchenPrintArr = kitchenPrintArr.concat([27,66,9,1]);//蜂鸣提醒
                            kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                            if(curOrderData.tableNo != null){
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'+curOrderData.tableNo));
                            }else{
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('座位号:：'));
                            }
                            kitchenPrintArr = kitchenPrintArr.concat([29,33,0]);//取消汉字倍宽高
                            kitchenPrintArr = kitchenPrintArr.concat([10]);
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat(gbk('下单人:：'+curOrderData.creatorName));
                            kitchenPrintArr = kitchenPrintArr.concat([10]);
                            // 
                            if(curOrderData.source != "EMPLOYEE" && this.deliveryEnabled){
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('派送人员:：'+curOrderData.creatorName));
                                kitchenPrintArr = kitchenPrintArr.concat([10]);
                            }
                            // 
                            kitchenPrintArr = kitchenPrintArr.concat(gbk('订单号:：'+curOrderData.code));
                            kitchenPrintArr = kitchenPrintArr.concat([10]);
                            kitchenPrintArr = kitchenPrintArr.concat(gbk('下单时间:：'+new Date(curOrderData.createTime).Format('yyyy/MM/dd-hh:mm')));
                            kitchenPrintArr = kitchenPrintArr.concat([10]);
                            kitchenPrintArr = kitchenPrintArr.concat(gbk('打印时间:：'+new Date().Format('yyyy/MM/dd-hh:mm')));
                            kitchenPrintArr = kitchenPrintArr.concat([10]);
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,1]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat([29,33,34]);//汉字倍宽高
                            kitchenPrintArr = kitchenPrintArr.concat(gbk(curOrderData.items[i].productName));
                            // 
                            if(curOrderData.items[i].specs && Array.isArray(curOrderData.items[i].specs) && curOrderData.items[i].specs.length){
                                let specs = curOrderData.items[i].specs.join("/");
                                kitchenPrintArr = kitchenPrintArr.concat(gbk("("+specs+")"));
                            }
                            //
                            kitchenPrintArr = kitchenPrintArr.concat(gbk('('+curOrderData.items[i].quantity+')份'));
                            // kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//要打印的商品
                            kitchenPrintArr = kitchenPrintArr.concat([10]);//换行 
                            // 
                            if(curOrderData.items[i].masterItemDtos && Array.isArray(curOrderData.items[i].masterItemDtos) && curOrderData.items[i].masterItemDtos.length){
                                curOrderData.items[i].masterItemDtos.forEach(it=>{
                                    if(it.kitchenPrintEnabled){
                                        kitchenPrintArr = kitchenPrintArr.concat(gbk('---配品:：'+it.productName));
                                        kitchenPrintArr = kitchenPrintArr.concat([10]);//换行
                                        kitchenPrintArr = kitchenPrintArr.concat(gbk('---数量:：'+it.quantity));
                                        kitchenPrintArr = kitchenPrintArr.concat([10]);//换行                    
                                        // kitchenPrintArr = kitchenPrintArr.concat(gbk('---单价:：'+(it.salesPrice/it.quantity).toFixed(2)));
                                        kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                                    }
                                })
                            }
                            // 
                            kitchenPrintArr = kitchenPrintArr.concat([29,33,17]);//汉字倍宽高
                            if(curOrderData.notes != null){
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'+curOrderData.notes));
                            }else{
                                kitchenPrintArr = kitchenPrintArr.concat(gbk('备注:：'));
                            }
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat([27,100,2]);//空格走纸
                            kitchenPrintArr = kitchenPrintArr.concat([29,86,0]);//切纸


                            if(parseInt(localStorage.getItem('kitchPrintCount'))===2){
                                kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//默认两份
                            }else if(parseInt(localStorage.getItem('kitchPrintCount'))===0){
                                kitchenPrintArr = [];
                            }
                            // kitchenPrintArr = kitchenPrintArr.concat(kitchenPrintArr);//默认两份
                            newkitchenPrintArr = newkitchenPrintArr.concat(kitchenPrintArr);
                        }
                        
                    }
                }
            }
            console.log("厨房打印end")
            if(IskitchenPrint){//厨房打印
                if(!localStorage.getItem('kitchIp')||!localStorage.getItem('kitchPort')){
                    alert('厨房打印失败！请设置IP和端口');
                    return;
                }
                printTcp_({ip:localStorage.getItem('kitchIp'),port:parseInt(localStorage.getItem('kitchPort'))}, newkitchenPrintArr);
            }

            if(hasOtherPrint){
                for(let key in printArr){
                        
                    let ipInfo = key.split("_");
                    // console.log(this.printData.goodArr[i])
                    // printTcp_({ip:localStorage.getItem('kitchIp'),port:parseInt(localStorage.getItem('kitchPort'))}, kitchenPrintArr);
                    // printTcp_({ip:ipInfo[0],port:ipInfo[1]}, printArr[key].printStr);
                    // if(localStorage.getItem("kitchPrintMode") == "WholeOrder"){
                        // this.surePrintForkitchenOneType(printArr[key].items);
                    // }else{
                    printTcp_({ip:ipInfo[0],port:ipInfo[1]}, printArr[key].printStr);
                    // }
                    
                }
            }
        },
        surePrintForTag(data,labelPrintData,printDeviceId=null){
            if(labelPrintData.length){
                console.log(labelPrintData)
                // 遍历商品数据
                for(let i=0;i<labelPrintData.length;i++){
                    console.log("标签自动打印start")
                    if(labelPrintData[i].id) {
                        // if(labelPrintData[i].labelEnabled){
                            let arr = [];
                            // arr = arr.concat(GBK.encode('SIZE 40 mm,30 mm\r\n'));
                            // arr = arr.concat(GBK.encode('GAP 2 mm,0 mm\r\n'));
                            // arr = arr.concat(GBK.encode('CODEPAGE 437\r\n'));
                            // arr = arr.concat(GBK.encode("CLS\r\n"));
                            arr = arr.concat(GBK.encode('SIZE 40mm,30mm\r\n'));
                            arr = arr.concat(GBK.encode('GAP 2 mm, 0 mm\r\n'));
                            // 
                            arr = arr.concat(GBK.encode('DENSITY 15\r\n'));
                            arr = arr.concat(GBK.encode('DIRECTION 0\r\n'));
                            arr = arr.concat(GBK.encode('SPEED 5\r\n'));
                            // 
                            arr = arr.concat(GBK.encode('CODEPAGE 437\r\n'));
                            arr = arr.concat(GBK.encode('BEEP\r\n'));
                            arr = arr.concat(GBK.encode("CLS\r\n"));
                            // arr = arr.concat(GBK.encode('TEXT 50,50,"TSS24.BF2",0,1,1,"你好"\r\n'));
                            if(labelPrintData[i].specs && Array.isArray(labelPrintData[i].specs) && labelPrintData[i].specs.length){
                                let specs = labelPrintData[i].specs.join("/");
                                // 座位号
                                let tableNo = data.tableNo;
                                // arr = arr.concat(GBK.encode("DENSITY 15\r\n"));
                                arr = arr.concat(GBK.encode('TEXT 10,10,"TSS24.BF2",0,1,1,'+`"座位号:${tableNo}"`+'\r\n'));
                                // arr = arr.concat(GBK.encode('TEXT 10,45,"TSS24.BF2",0,1,1,'+`"${tableNo}"`+'\r\n'));
                                // arr = arr.concat(GBK.encode('TEXT 10,45,"TSS24.BF2",0,1,1,'+`"${tableNo}"`+'\r\n'));
                                // 品名
                                let goodsName =labelPrintData[i].productName;
                                // arr = arr.concat(GBK.encode('TEXT 10,75,"TSS24.BF2",0,1,1,"品名:"\r\n'));
                                arr = arr.concat(GBK.encode('TEXT 10,50,"TSS24.BF2",0,1,1,'+`"品名:${goodsName}"`+'\r\n'));

                                // 规格
                                // arr = arr.concat(GBK.encode('TEXT 10,75,"TSS24.BF2",0,1,1,"品名:"\r\n'));
                                arr = arr.concat(GBK.encode('TEXT 10,88,"TSS24.BF2",0,1,1,'+`"规格:${specs}"`+'\r\n'));
                            }else{
                                // 店铺名
                                let storeName = this.storeName.length>9?this.storeName.substring(0,5)+'...':this.storeName;
                                arr = arr.concat(GBK.encode('TEXT 10,10,"TSS24.BF2",0,1,1,'+`"店铺名:${storeName}"`+'\r\n'));
                                // 座位号
                                let tableNo = data.tableNo;
                                // arr = arr.concat(GBK.encode("DENSITY 15\r\n"));
                                arr = arr.concat(GBK.encode('TEXT 10,50,"TSS24.BF2",0,1,1,'+`"座位号:${tableNo}"`+'\r\n'));
                                // arr = arr.concat(GBK.encode('TEXT 10,45,"TSS24.BF2",0,1,1,'+`"${tableNo}"`+'\r\n'));
                                // arr = arr.concat(GBK.encode('TEXT 10,45,"TSS24.BF2",0,1,1,'+`"${tableNo}"`+'\r\n'));
                                // 品名
                                let goodsName =labelPrintData[i].productName;
                                // arr = arr.concat(GBK.encode('TEXT 10,75,"TSS24.BF2",0,1,1,"品名:"\r\n'));
                                arr = arr.concat(GBK.encode('TEXT 10,88,"TSS24.BF2",0,1,1,'+`"品名:${goodsName}"`+'\r\n'));
                            }
                            // 价格
                            let price = (labelPrintData[i].salesPrice/labelPrintData[i].quantity).toFixed(2);
                            arr = arr.concat(GBK.encode('TEXT 10,125,"TSS24.BF2",0,1,1,'+`"价格:${price}元"`+'\r\n'));

                            // 时间
                            let time = new Date(data.createTime).Format('yy-MM-dd hh:mm');
                            arr = arr.concat(GBK.encode('TEXT 10,160,"TSS24.BF2",0,1,1,'+`"时间:${time}"`+'\r\n'));


                            // 此打印为当前订单的第几单
                            let nowCount = `${i+1}/${labelPrintData.length}`;
                            let notes = data.notes;
                            arr = arr.concat(GBK.encode('TEXT 10,195,"TSS24.BF2",0,1,1,'+`"杯数:${nowCount};${notes?('备注:'+notes):notes}"`+'\r\n'));
                        // }
                            arr = arr.concat(GBK.encode('PRINT 1\r\n '));
                            let testData = arr;
                            console.log(testData);
                            console.log("标签自动打印end")
                            if(printDeviceId){
                                printForTag(printDeviceId,testData);
                            }else{
                                printForTag((localStorage.getItem('printIdForTag')?localStorage.getItem('printIdForTag'):''),testData);
                            }
                    }
                }
                
            }
        },
        // 
        //连接服务器的函数
        connect: function () {
            var socket = new SockJS(WS_API_URL+'gs-guide-websocket');
            // var socket = new SockJS('https://api.huoxingy.com/gs-guide-websocket');
            this.stompClient = Stomp.over(socket);
            let that = this;
            this.stompClient.connect({'Auth-Token': this.token}, function (frame) {
                that.stompClient.ws.onerror = function ( evnt ) {
                    that.connect();
                }
                that.stompClient.ws.onclose = function ( evnt ) {
                    that.connect();
                }
                // that.sendMessage();
                //订阅服务器发送来的消息
                // that.stompClient.subscribe('/message/'+that.token+"/"+that.storeInfo.storeId, function (event) {
                //     let res = JSON.parse(event.body);
                //     that.updatesTime = res.lastTimestamp;
                //     that.orderNum += res.count;
                //     if ( res.count > 0 ) {
                //         if ( that.curVoiceName ) {
                //             $('.audio').remove();
                //             $('.index').append($('<audio style="display:none" controls="" class="audio" src="../../../static/voice/'+that.curVoiceName+'" autoplay="autoplay" id="audios"></audio>'));
                //         }
                //     }
                // });
                that.stompClient.subscribe('/message/'+that.storeInfo.storeId, function (event) {
                    console.log("我收到了服务器消息");
                    let res = JSON.parse(event.body);
                    if(res.source == "CALL" || res.source == "REWARD" || res.source == "MAKE" || res.source == "DELIVERYING"){
                        console.log("call");
                        return;
                    }
                    // 
                    // if(!localStorage.getItem("orders")){
                    //     let orders = [];
                    //     orders.push(res.orderId);
                    //     localStorage.setItem("orders",JSON.stringify(orders));
                    //     that.updatesTime = res.lastTimestamp;
                    //     that.orderNum += res.count;
                    //     if ( res.count > 0 ) {
                    //         if ( that.curVoiceName ) {
                    //             $('.audio').remove();
                    //             $('.index').append($('<audio style="display:none" controls="" class="audio" src="../../../static/voice/'+that.curVoiceName+'" autoplay="autoplay" id="audios"></audio>'));
                    //         }
                    //     }
                    // }else{
                    //     let nowOrders = localStorage.getItem("orders");
                    //     nowOrders = JSON.parse(nowOrders);
                    //     let flag = false;
                    //     for(let i=0;i<nowOrders.length;i++){
                    //         if(res.orderId == nowOrders[i]){
                    //             flag = true;
                    //         }
                    //     }
                    //     if(!flag){
                    //         nowOrders.push(res.orderId);
                    //         localStorage.setItem("orders",JSON.stringify(nowOrders));

                    //         that.updatesTime = res.lastTimestamp;
                    //         that.orderNum += res.count;
                    //         if ( res.count > 0 ) {
                    //             if ( that.curVoiceName ) {
                    //                 $('.audio').remove();
                    //                 $('.index').append($('<audio style="display:none" controls="" class="audio" src="../../../static/voice/'+that.curVoiceName+'" autoplay="autoplay" id="audios"></audio>'));
                    //             }
                    //         }
                    //     }
                    // }
                    // 
                    if(res.source == "BOOK"){
                        // that.orderNum++;
                        that.waitNum++;
                        // return;
                    }
                    if(res.source == "LEASE"){
                        that.leaseNum++;
                    }

                    that.updatesTime = res.lastTimestamp;
                    that.orderNum += res.count;
                    that.printCount++;
                    if ( res.count > 0 ) {
                        // 
                        // let isAutoPrintOrder = that.isAutoPrintOrder;
                        // console.log(isAutoPrintOrder)
                        // if(isAutoPrintOrder){
                        //     console.log("res.orderId",res.orderId);
                        //     setTimeout(()=>{
                        //         that.getOrderDetail(res.orderId);
                        //     },250*that.printCount)
                        // }
                        if ( that.curVoiceName ) {
                            $('.audio').remove();
                            $('.index').append($('<audio style="display:none" controls="" class="audio orderAudio" src="../../../static/voice/'+that.curVoiceName+'" id="audios"></audio>'));
                            // setTimeout(()=>{
                                let audioDevice = "";
                                audioDevice = localStorage.getItem("audioDevice");
                                if(audioDevice){
                                    console.log("$.orderAudio",$(".orderAudio")[0]);
                                    console.log(`Audio is being output on ${audioDevice}`);
                                    // 
                                    let deviceId = "";
                                    that.allAudioOptions.forEach(it=>{
                                        if(it.label == audioDevice){
                                            deviceId = it.deviceId;
                                        }
                                    })
                                    // 
                                    console.log("deviceId",deviceId);
                                    $(".orderAudio")[0].setSinkId(deviceId);
                                }
                                $(".orderAudio")[0].play();
                                console.log("jin")
                                $(".orderAudio").on("playing",function () {
                                    let orderVoiceVolum  = localStorage.getItem("orderVoiceVolum");
                                    console.log("orderVoiceVolum",orderVoiceVolum)
                                    if(orderVoiceVolum){
                                        $(".orderAudio")[0].volume = Number(JSON.parse(orderVoiceVolum) / 100).toFixed(2);
                                    }
                                })
                            // },100);
                            
                        }
                    }
                });

                // that.timer = setInterval(()=>{
                //     that.sendMessage();
                // }, 6000);
                // that.timer = setInterval(()=>{
                //     that.sendMessage();
                // }, 6000);

            });
            this.stompClient.ws.onclose = function ( evnt ) {
                setTimeout(()=>{
                    that.connect(); 
                }, 1000);
            }
            this.stompClient.debug = function(str) {
                // str 参数即为 debug 信息
            // append the debug log to a #debug div somewhere in the page using JQuery:
                console.log(str);
            };
        },
       
        //发送聊天信息
        sendMessage: function () {
            
            this.stompClient.send('/app/todo-orders/updates-count/'+this.token, {}, JSON.stringify({'lastTimestamp': this.updatesTime,'storeId':this.storeInfo.storeId}));
        },
        //  //发送聊天信息(语音服务)
        // sendMessageNotice: function () {
        //     this.stompClientNotice.send('/app/notice/'+this.token, {}, JSON.stringify({'lastTimestamp': this.noticeUpdatesTime,'storeId':this.storeInfo.storeId}));
        // },
        // 断开ws连接
        disconnect: function () {
            if (this.stompClient !== null) {
                this.stompClient.disconnect();
            }
        },// 断开ws连接(语音服务)
       
        getNoticeFn(val){
            this.$http.get(this.storeInfo.storeId+'/notic'+'?page='+(val-1)+'&size=10').then((res)=>{
                this.noticeBtn = true;
                this.noticeList = res.data.content;
                this.noticeTotalElements = res.data.totalElements;
            })
        },
        goInv(){
            window.open('https://inventory.huoxingy.com/#/login');
        },
        getRentOrderInfo(numId){
            if(!this.storeInfo || !this.storeInfo.storeId){
                return;
            }
            return new Promise((resolve,reject)=>{
                this.$http({
                    url:`${API_BASE_URL}v1/call/order/by/id`,
                    method:"POST",
                    data:{
                        numId,
                        storeId:this.storeInfo.storeId
                    }
                }).then(res=>{
                    console.log("rentRes",res.data);
                    if(res.data && Array.isArray(res.data) && res.data.length){
                        resolve(res.data);
                    }
                }).catch(err=>{
                    reject(err);
                })
            })
        },
        // 
        getIpArr(){
            if(!this.storeInfo || !this.storeInfo.storeId){
                return;
            }
            this.$http({
                url:"region/list",
                method:"POST",
                data:{
                    storeId:this.storeInfo.storeId
                }
            }).then(res=>{
                console.log(res);
                let ipObj = {};
                if(res.data && Array.isArray(res.data) && res.data.length){
                    res.data.forEach(it=>{
                        if(it.nums && Array.isArray(it.nums) && it.nums.length){
                            it.nums.forEach(ite=>{
                                let ipSplitArr = ite.ipAddress.split(".");
                                ipObj[
                                    `${ipSplitArr[0]}.${ipSplitArr[1]}.${ipSplitArr[2]}.`
                                ] = [];
                            })
                        }
                    })
                    res.data.forEach(it=>{
                        if(it.nums && Array.isArray(it.nums) && it.nums.length){
                            it.nums.forEach(ite=>{
                                for(let k in ipObj){
                                    if(ite.ipAddress.indexOf(k)!=-1){
                                        ipObj[k].push({
                                            ip:ite.ipAddress,
                                            id:ite.id,
                                            name:ite.name,
                                            status:ite.status,
                                            regionId:it.id
                                        });
                                    }
                                }
                            })
                        }
                    })
                }
                console.log("ipObj",ipObj);
                if(ipObj){
                    let ipRegions = Object.keys(ipObj);
                    console.log(ipRegions.join("|"));
                    if(ipRegions && Array.isArray(ipRegions) && ipRegions.length){
                        setTimeout(async ()=>{
                            clearInterval(this.ipTimer);
                            try {
                                let pingRes = await getIpSegmentPingResult();
                                console.log("pingRes,pingRes",pingRes)
                                if(!pingRes){
                                    await setIpSegment(ipRegions.join("|"));
                                }
                            } catch (error) {
                                console.log(error)
                            }
                            this.ipTimer = setInterval(async ()=>{
                                let pingRes = await getIpSegmentPingResult();
                                console.log("pingRes",pingRes);
                                let tempIps = pingRes.split("|");
                                let ips = []
                                if(tempIps && Array.isArray(tempIps) && tempIps.length){
                                    tempIps.forEach(it=>{
                                        let ipStr = it.split(",");
                                        if(ipStr && Array.isArray(ipStr) && ipStr.length){
                                            let ipFront = ipStr[0];
                                            if(ipStr.length > 1){
                                                for(let i=1;i<ipStr.length;i++){
                                                    if(ipStr[i].indexOf(":1")!=-1){
                                                        let ipEnd = ipStr[i].split(":")[0];
                                                        ips.push(`${ipFront}${ipEnd}`);
                                                    }
                                                }
                                            }
                                        }
                                    })
                                }
                                console.log(ips);
                                let freeNumIds = [];
                                let busyNumIds = [];
                                let busyNums = [];
                                for(let k in ipObj){
                                    if(ipObj[k] && Array.isArray(ipObj[k]) && ipObj[k].length){
                                        ipObj[k].forEach(it=>{
                                            if(ips.indexOf(it.ip)!=-1){
                                                busyNums.push({
                                                    id:it.id,
                                                    name:it.name,
                                                });
                                                busyNumIds.push(it.id);
                                            }else{
                                                if(it.status!=2){
                                                    freeNumIds.push(it.id);
                                                }
                                            }
                                        })
                                    }
                                }
                                console.log("freeNumIds",freeNumIds);
                                console.log("busyNumIds",busyNumIds);
                                let tempBusyNums = localStorage.getItem("busyNums");
                                if(tempBusyNums){
                                    let voiceArr = [];
                                    let tempVoiceObjArr = [];
                                    tempBusyNums = JSON.parse(tempBusyNums);
                                    if(tempBusyNums && Array.isArray(tempBusyNums) && tempBusyNums.length){
                                        tempBusyNums.forEach(it=>{
                                            if(busyNumIds.indexOf(it.id)==-1){
                                                voiceArr.push(it.name);
                                                tempVoiceObjArr.push({
                                                    id:it.id,
                                                    name:it.name,
                                                });
                                            }
                                        })
                                    }
                                    // let pAll = [];
                                    // if(tempVoiceObjArr && tempVoiceObjArr.length){
                                    //     tempVoiceObjArr.forEach(it=>{
                                    //         pAll.push(this.getRentOrderInfo(it.id));
                                    //     })
                                    // }
                                    // let pRes = await Promise.all(pAll);
                                    // console.log("pRes",pRes);
                                    // let notReturnNumInfo = [];
                                    // if(pRes && Array.isArray(pRes) && pRes.length){
                                    //     pRes.forEach(it=>{
                                    //         if(it && Array.isArray(it) && it.length){
                                    //             notReturnNumInfo.push(it[0].numName);
                                    //         }
                                    //     })
                                    // }
                                    if(voiceArr.length){
                                        let offOnVoiceNotify = sessionStorage.getItem("offOnVoiceNotify");
                                        console.log("offOnVoiceNotify",offOnVoiceNotify)
                                        if((offOnVoiceNotify == true || offOnVoiceNotify == "true") && this.posCallEnabled){
                                            this.playVoice(voiceArr,[]);
                                        }
                                        try {
                                            let leaseProductEnabled = sessionStorage.getItem("leaseProductEnabled");
                                            if(leaseProductEnabled=="true"){
                                                setTimeout(async ()=>{
                                                    let pAll = [];
                                                    if(tempVoiceObjArr && tempVoiceObjArr.length){
                                                        tempVoiceObjArr.forEach(it=>{
                                                            pAll.push(this.getRentOrderInfo(it.id));
                                                        })
                                                    }
                                                    let pRes = await Promise.all(pAll);
                                                    console.log("pRes",pRes);
                                                    let notReturnNumInfo = [];
                                                    if(pRes && Array.isArray(pRes) && pRes.length){
                                                        pRes.forEach(it=>{
                                                            if(it && Array.isArray(it) && it.length){
                                                                notReturnNumInfo.push(it[0].numName);
                                                            }
                                                        })
                                                    }
                                                    this.playVoiceForRent(notReturnNumInfo);
                                                },1000*60)
                                            }
                                        } catch (error) {
                                            
                                        }
                                        
                                    }
                                }
                                localStorage.setItem("busyNums",JSON.stringify(busyNums));
                                this.refreshSites(freeNumIds,busyNumIds);
                            },30*1000);
                        },1000)
                    }
                    
                }
            })
        },
        playVoiceForRent(voiceArr){
            try {
                let returnCallEnabled = sessionStorage.getItem("returnCallEnabled");
                if(returnCallEnabled!="true"){
                    return;
                }
            } catch (error) {
                
            }
            let flag = false;
            $(".audio").on("playing",function () {
                flag = true;
            });
            $(".audio").on("ended",function () {
                flag = false;
            });
            if(this.playingFlag){
                flag = true;
            }else{
                flag = false;
            }
            
            if(this.voiceTimer){
                clearInterval(this.voiceTimer);
            }
            // 
            // let audios = [];
            let status = true;
            let numNameStr = "";
            voiceArr.forEach(it=>{
                // $('.index').append($('<audio style="display:none;" controls="" class="ipAudio" src="'+API_BASE_URL+'v1/pos/speech?tex=工作人员请注意,,,,,'+it+'号机已下机&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="ipAudio"></audio>')); 
                // audios.push(audio);
                numNameStr += `${it}号机,,,,,,,,,`;
            });
            let frontMessage = "工作人员请注意,,,,,";
            let backMessage = ",,,,,,请及时回收租赁设备,,,,,,保持卫生";
            let audio = `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?tex=${frontMessage}${numNameStr}有未归还租赁设备${backMessage}&vol=9&per=0&spd=5&pit=5" id="ipAudio"></audio>`; 
            // 
            this.voiceTimer = setInterval(()=>{
                let that = this;
                if(!flag){
                    $('.index').append(audio);
                    // 
                    setTimeout(()=>{
                        let audioDeviceForOffline = "";
                        audioDeviceForOffline = localStorage.getItem("audioDeviceForOffline");
                        if(audioDeviceForOffline){
                            console.log("$.ipAudio",$(".ipAudio")[0]);
                            console.log(`ipAudio is being output on ${audioDeviceForOffline}`);
                            // 
                            let deviceId = "";
                            that.allAudioOptions.forEach(it=>{
                                if(it.label == audioDeviceForOffline){
                                    deviceId = it.deviceId;
                                }
                            })
                            // 
                            console.log("deviceId",deviceId);
                            $(".ipAudio")[0].setSinkId(deviceId);
                        }
                        $(".ipAudio")[0].play();
                        // 
                        $(".ipAudio").on("playing",function () {
                            let offlineVoiceVolum  = localStorage.getItem("offlineVoiceVolum");
                            if(offlineVoiceVolum){
                                $(".ipAudio")[0].volume = Number(JSON.parse(offlineVoiceVolum) / 100).toFixed(2);
                            }
                            clearInterval(that.voiceTimer);
                        })
                        $(".ipAudio").on("ended",function () {
                            this.remove();
                        })
                    },100)
                }
            },5000);
        },
        // 
        convertCurrency(num) {
            const chineseNum = {
                digits: ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'],
                units: ['', '十', '百', '千'],
                bigUnits: ['', '万', '亿', '万亿']
            };

            function convertInteger(numStr) {
                if (numStr === '0') return '零';
                let result = '';
                let zeroCount = 0;
                const len = numStr.length;

                for (let i = 0; i < len; i++) {
                    const digit = parseInt(numStr[i]);
                    const pos = len - i - 1;
                    const unitIndex = pos % 4;
                    const bigUnitIndex = Math.floor(pos / 4);

                    if (digit === 0) {
                        zeroCount++;
                    } else {
                        if (zeroCount > 0) {
                            result += '零';
                            zeroCount = 0;
                        }
                        // 处理十位的特殊读法（例如：10读作"十"，110读作"一百一十"）
                        if (digit === 1 && unitIndex === 1 && i === 0) {
                            result += chineseNum.units[unitIndex];
                        } else {
                            result += chineseNum.digits[digit] + chineseNum.units[unitIndex];
                        }
                    }

                    // 添加大单位（万/亿）
                    if (unitIndex === 0 && bigUnitIndex > 0) {
                        result += chineseNum.bigUnits[bigUnitIndex];
                    }
                }

                return result.replace(/零+$/, '') || '零';
            }

            function convertDecimal(decimalStr) {
                return decimalStr.split('').map(c => chineseNum.digits[parseInt(c)]).join('');
            }

            // 主处理逻辑
            let numStr = typeof num === 'string' ? num : String(num);
            let isNegative = false;
            
            // 处理负数
            if (numStr.startsWith('-')) {
                isNegative = true;
                numStr = numStr.slice(1);
            }

            const [integerPart, decimalPart] = numStr.split('.');
            let result = convertInteger(integerPart || '0');

            // 处理小数部分
            if (decimalPart) {
                const isAllZero = decimalPart.split('').every(c => c === '0');
                if (!isAllZero) {
                    result += '点' + convertDecimal(decimalPart);
                }
            }

            return (isNegative ? '负' : '') + result;
        },
      generateNumVoice(voiceNumbers){
        let voiceArr = [];
        if(voiceNumbers && Array.isArray(voiceNumbers)){
          voiceNumbers.forEach(it=>{
            if(it){
              let itArr = String(it).split("");
              itArr.forEach(ite=>{
                voiceArr.push(`<audio style="display:none" id='ipAudio' class="ipAudio" src='../../../static/voice/cgdz/${ite}.mov'></audio>`);
              })
              voiceArr.push(`<audio style="display:none" id='ipAudio' class="ipAudio" src='../../../static/voice/cgdz/号机.mov'></audio>`);
            }
          })
        }
        return voiceArr;
      },
      playVoice(voiceArr,notReturnNumInfo){
            return;
            let flag = false;
            $(".audio").on("playing",function () {
                flag = true;
            });
            $(".audio").on("ended",function () {
                flag = false;
            });
            if(this.voiceTimer){
                clearInterval(this.voiceTimer);
            }
            // 
            // let audios = [];
            let status = true;
            this.playingFlag = true;
            let numNameStr = "";
            voiceArr.forEach((it,ind)=>{
                voiceArr[ind] = this.convertCurrency(Number(it));
                // $('.index').append($('<audio style="display:none;" controls="" class="ipAudio" src="'+API_BASE_URL+'v1/pos/speech?tex=工作人员请注意,,,,,'+it+'号机已下机&vol=9&per=0&spd=5&pit=5" autoplay="autoplay" id="ipAudio"></audio>')); 
                // audios.push(audio);
                // numNameStr += `${it}号机,,,,,,,,,`;
            });
            let offOnVoiceMessage = sessionStorage.getItem("offOnVoiceMessage");
            let frontMessage = "工作人员请注意,,,,,";
            let backMessage = ",,,,,,请及时清理桌面,,,,,,保持卫生";
            if(offOnVoiceMessage && offOnVoiceMessage.indexOf("**号机已下机")!=-1){
                try {
                    let message = offOnVoiceMessage.split("**号机已下机");
                    if(message && Array.isArray(message) && message.length>1){
                        frontMessage = message[0];
                        backMessage = message[1];
                    }
                } catch (error) {
                    console.log(error);
                }
                console.log("frontMessage",frontMessage);
                console.log("backMessage",backMessage);
            }
            // let audio = `<audio style="display:none;" controls="" class="ipAudio" src="${API_BASE_URL}v1/pos/speech?tex=${frontMessage}${numNameStr}已下机${backMessage}&vol=9&per=0&spd=5&pit=5" id="ipAudio"></audio>`; 
            // 
            let audios = [];
            let frontMessageAudio = `<audio style="display:none;" controls="" class="ipAudio" src="../../../static/voice/xiaji/gzryqzy.mp3" id="ipAudio"></audio>`; 
            let numberAudios = this.generateNumVoice(voiceArr);
            let backMessageAudio = `<audio style="display:none;" controls="" class="ipAudio" src="../../../static/voice/xiaji/yxj.mp3" id="ipAudio"></audio>`; 
            audios = [frontMessageAudio,...numberAudios,backMessageAudio],
            console.log("audios",audios);
            // 
            this.voiceTimer = setInterval(()=>{
                let that = this;
                if(!flag){
                  if(audios && Array.isArray(audios) && audios.length){
                    let audioIndex = 0;
                    if(!status){
                      return;
                    }
                    status = false;//正在播放
                    function playAudio(audioIndex){
                        if(audioIndex < audios.length){
                            $('.index').append(audios[audioIndex]);
                            console.log("正在播放"+audioIndex);
                            console.log('$("#ipAudio")',$(".ipAudio"))
                            // 
                            let audioDeviceForOffline = "";
                            audioDeviceForOffline = localStorage.getItem("audioDeviceForOffline");
                            try {
                              if(audioDeviceForOffline){
                                  console.log("$.ipAudio",$(".ipAudio")[0]);
                                  console.log(`ipAudio is being output on ${audioDeviceForOffline}`);
                                  // 
                                  let deviceId = "";
                                  that.allAudioOptions.forEach(it=>{
                                      if(it.label == audioDeviceForOffline){
                                          deviceId = it.deviceId;
                                      }
                                  })
                                  // 
                                  console.log("deviceId",deviceId);
                                  $(".ipAudio")[0].setSinkId(deviceId);
                              }
                            } catch (error) {
                              console.log("error",error);
                            }
                            $(".ipAudio")[0].play();
                            // 
                            try {
                                $("#ipAudio").on("playing",function () {
                                    let offlineVoiceVolum  = localStorage.getItem("offlineVoiceVolum");
                                    if(offlineVoiceVolum){
                                        $(".ipAudio")[0].volume = Number(JSON.parse(offlineVoiceVolum) / 100).toFixed(2);
                                    }
                                })
                            } catch (error) {
                              console.log(error)
                            }
                            try {
                              $("#ipAudio").on("ended",function () {
                                  this.remove();
                                  playAudio(audioIndex+1);
                              })
                            } catch (error) {
                              console.log(error)
                            }
                            
                        }else{
                            console.log("播放完毕");
                            audios = [];
                            clearInterval(that.voiceTimer);
                            that.playingFlag = false;
                            status = true;
                            $("#ipAudio").remove();
                        }
                    }
                    playAudio(audioIndex);
                  }
                    // $('.index').append(audio);
                    // // 
                    // setTimeout(()=>{
                    //     let audioDeviceForOffline = "";
                    //     audioDeviceForOffline = localStorage.getItem("audioDeviceForOffline");
                    //     if(audioDeviceForOffline){
                    //         console.log("$.ipAudio",$(".ipAudio")[0]);
                    //         console.log(`ipAudio is being output on ${audioDeviceForOffline}`);
                    //         // 
                    //         let deviceId = "";
                    //         that.allAudioOptions.forEach(it=>{
                    //             if(it.label == audioDeviceForOffline){
                    //                 deviceId = it.deviceId;
                    //             }
                    //         })
                    //         // 
                    //         console.log("deviceId",deviceId);
                    //         $(".ipAudio")[0].setSinkId(deviceId);
                    //     }
                    //     $(".ipAudio")[0].play();
                    //     // 
                    //     $(".ipAudio").on("playing",function () {
                    //         let offlineVoiceVolum  = localStorage.getItem("offlineVoiceVolum");
                    //         if(offlineVoiceVolum){
                    //             $(".ipAudio")[0].volume = Number(JSON.parse(offlineVoiceVolum) / 100).toFixed(2);
                    //         }
                    //         clearInterval(that.voiceTimer);
                    //     })
                    //     $(".ipAudio").on("ended",function () {
                    //         this.remove();
                    //         that.playingFlag = false;
                    //         // that.playVoiceForRent(notReturnNumInfo);
                    //     })
                    // },100)
                    // 
                    // if(audios && audios.length){
                    //     let audioIndex = 0;
                    //     function playAudio(audioIndex){
                    //         if(audioIndex < audios.length){
                    //             $('.index').append(audios[audioIndex]);
                                
                    //             $(".ipAudio").on("playing",function () {
                    //                 status = false;//正在播放
                    //             })
                    //             $(".ipAudio").on("ended",function () {
                    //                 this.remove();
                    //                 playAudio(audioIndex+1);
                    //             })
                    //         }else{
                    //             console.log("播放完毕");
                    //             clearInterval(this.voiceTimer);
                    //             audios = [];
                    //             status = true;
                    //         }
                    //     }
                    //     playAudio(audioIndex);
                    //     return;
                    // }
                }
            },5000);
        },
        refreshSites(freeNumIds,busyNumIds){
            const pFree = new Promise((resolve,reject)=>{
                this.$http({
                    url:"update/num",
                    method:"POST",
                    data:{
                        numIds:freeNumIds,
                        status:0,
                        dateExpiredTime:null,
                        storeId:this.storeInfo.storeId,
                    }
                }).then(res=>{
                    resolve(res);
                }).catch(err=>{
                    reject(err);
                })
            })

            const pBusy = new Promise((resolve,reject)=>{
                this.$http({
                    url:"update/num",
                    method:"POST",
                    data:{
                        numIds:busyNumIds,
                        status:1,
                        dateExpiredTime:null,
                        storeId:this.storeInfo.storeId,
                    }
                }).then(res=>{
                    resolve(res);
                }).catch(err=>{
                    reject(err);
                })
            })
            let pArr = [];
            if(freeNumIds && Array.isArray(freeNumIds) && freeNumIds.length){
                pArr.push(pFree);
            }
            if(busyNumIds && Array.isArray(busyNumIds) && busyNumIds.length){
                pArr.push(pBusy);
            }
            Promise.all(pArr).then(res=>{
                console.log(res);
            })
            
        },
        getPosSetting(storeId){
            this.$http({
                url:"store-print-config",
                method:"GET",
                params:{
                    storeId
                }
            }).then(res=>{
                console.log("res,res",res);
                if(res.data){
                    this.settingObj = {
                        orderVoiceName: res.data.audio, // 订单提示音
                        autoPrint: JSON.parse(res.data.receiptAuto) ? JSON.parse(res.data.receiptAuto).autoPrint : "ON", // 自动打印
                        totalClassify: res.data.receiptType, // 自动打印
                        pasterName: localStorage.getItem('pasterName')?ocalStorage.getItem('pasterName'):"", // 小票打印
                        printId: localStorage.getItem('printId')?localStorage.getItem('printId'):"", // 厨房打印IP
                        kitchIp: res.data.kitchenIp, // 厨房打印端口
                        kitchPort: res.data.kitchenPort, // 厨房打印端口
                        kitchPrintCount: String(res.data.kitchenAmount), // 厨房打印端口
                        isTagPrint: res.data.allowLabel, // 厨房打印端口
                        printIdForSale: res.data.receiptPrintId, // 厨房打印端口
                        printIdForTag: res.data.labelPrintId, // 厨房打印端口
                        // 
                        payVoiceVolum: res.data.paidVolume,
                        orderVoiceVolum: res.data.orderVolume,
                        offlineVoiceVolum: res.data.shutdownVolume,
                    }
                    let autoPrints = JSON.parse(localStorage.getItem('autoPrint'));
                    autoPrints.autoPrint = this.settingObj.autoPrint;
                    localStorage.setItem('orderVoiceName', this.settingObj.orderVoiceName ? this.settingObj.orderVoiceName : "");
                    localStorage.setItem('autoPrint', JSON.stringify(autoPrints));
                    localStorage.setItem('totalClassify', this.settingObj.totalClassify);
                    localStorage.setItem('pasterName', this.settingObj.pasterName);
                    localStorage.setItem('printId', this.settingObj.printId ? this.settingObj.printId : "");
                    localStorage.setItem('kitchIp', this.settingObj.kitchIp ? this.settingObj.kitchIp : "");
                    localStorage.setItem('kitchPort', this.settingObj.kitchPort ? this.settingObj.kitchPort : "");
                    localStorage.setItem('kitchPrintCount', this.settingObj.kitchPrintCount);
                    localStorage.setItem('isTagPrint', this.settingObj.isTagPrint);
                    localStorage.setItem('printIdForSale', this.settingObj.printIdForSale ? this.settingObj.printIdForSale : "");
                    localStorage.setItem('printIdForTag', this.settingObj.printIdForTag ? this.settingObj.printIdForTag : "");
                    // 
                    localStorage.setItem('payVoiceVolum', this.settingObj.payVoiceVolum);
                    localStorage.setItem('orderVoiceVolum', this.settingObj.orderVoiceVolum);
                    localStorage.setItem('offlineVoiceVolum', this.settingObj.offlineVoiceVolum);
                }else{
                    // this.settingObj = {
                    //     orderVoiceName: localStorage.getItem('orderVoiceName'), // 订单提示音
                    //     autoPrint: JSON.parse(localStorage.getItem('autoPrint')).autoPrint, // 自动打印
                    //     totalClassify: localStorage.getItem('totalClassify'), // 自动打印
                    //     pasterName: localStorage.getItem('pasterName')?localStorage.getItem('pasterName'):"", // 小票打印
                    //     printId: localStorage.getItem('printId')?localStorage.getItem('printId'):"", // 厨房打印IP
                    //     kitchIp: localStorage.getItem('kitchIp'), // 厨房打印端口
                    //     kitchPort: localStorage.getItem('kitchPort'), // 厨房打印端口
                    //     kitchPrintCount: localStorage.getItem('kitchPrintCount'), // 厨房打印端口
                    //     isTagPrint: localStorage.getItem('isTagPrint'), // 厨房打印端口
                    //     printIdForSale: localStorage.getItem('printIdForSale'), // 厨房打印端口
                    //     printIdForTag: localStorage.getItem('printIdForTag'), // 厨房打印端口
                    //     // 
                    //     payVoiceVolum: localStorage.getItem('payVoiceVolum') ? Number(localStorage.getItem('payVoiceVolum')) : 30,
                    //     orderVoiceVolum: localStorage.getItem('orderVoiceVolum') ? Number(localStorage.getItem('orderVoiceVolum')) : 50,
                    //     offlineVoiceVolum: localStorage.getItem('offlineVoiceVolum') ? Number(localStorage.getItem('offlineVoiceVolum')) : 100,
                    // }
                    // let autoPrints = JSON.parse(localStorage.getItem('autoPrint'));
                    // autoPrints.autoPrint = this.settingObj.autoPrint;
                    // // 
                    // this.$http({
                    //     url:"store-print-config",
                    //     method:"POST",
                    //     data:{
                    //         storeId,
                    //         receiptAuto:JSON.stringify(autoPrints),
                    //         receiptType:this.settingObj.totalClassify,
                    //         allowLabel:this.settingObj.isTagPrint,
                    //         labelPrintId:this.settingObj.printIdForTag,
                    //         receiptPrintId:this.settingObj.printIdForSale,
                    //         kitchenIp:this.settingObj.kitchIp,
                    //         kitchenPort:this.settingObj.kitchPort,
                    //         kitchenAmount:this.settingObj.kitchPrintCount,
                    //         audio:this.settingObj.orderVoiceName,
                    //         // 
                    //         paidVolume: this.settingObj.payVoiceVolum,
                    //         orderVolume: this.settingObj.orderVoiceVolum,
                    //         shutdownVolume: this.settingObj.offlineVoiceVolum,
                    //     }
                    // }).then(res=>{
                        
                    // })
                    // 
                }
                console.log("settingObj,res",this.settingObj);
                this.$forceUpdate();
            }).catch(err=>{
            })
        },
        testSelAudio(){
            // navigator.webkitGetUserMedia({
            //     audio: true
            // }, (stream) => {
            //     console.log("stream: ", stream);
            // }, (error) => {
            //     console.log("error: ", error);
            // });
            // let _this = this;
            // async function queryUserMedia() {
            //     navigator.mediaDevices.getUserMedia( { audio: true } );
            // }
            // async function getListOfDevices() {
            //     const all_devs = await navigator.mediaDevices.enumerateDevices();
            //     console.log("all_devs",all_devs)
            //     const audioouts = all_devs.filter( ({ kind }) => kind === "audiooutput" );
            //     _this.audioOptions = audioouts;
            // }
            // const query = await navigator.permissions.query( { name: "microphone" } );
            // console.log("query",query)
            // switch( query.state ) {
            //     case "denied": throw new Error('denied');
            //     case "prompt":
            //         await queryUserMedia();
            //         await getListOfDevices();
            //         break;
            //     case "granted": await getListOfDevices();
            // }
            // console.log("navigator.permissions",navigator.permissions);
            // const constraints = window.constraints = {
            //     audio: true,
            // }

            // try {
            //     navigator.getUserMedia(constraints,(res)=>{console.log("dsfdfd",res)},(err)=>{console.log("dsfdfd_err",err)})
            // } catch (error) {
                
            // }
            // try {
            //     navigator.mediaDevices.getUserMedia( constraints ).then(res=>{
            //         console.log("getUserMedia_res",res);
            //     }).catch(err=>{
            //         console.log("getUserMedia_err",err);
            //     });
            // } catch (error) {
                
            // }
            // const deviceInfo = await navigator.mediaDevices.selectAudioOuput();
            navigator.mediaDevices.enumerateDevices().then(res=>{
                const audioDevices = res.filter((device) => device.kind === "audiooutput");
                console.log("navigator.mediaDevices",audioDevices);
                let groupKey = {};
                audioDevices.forEach(it=>{
                    groupKey[it.groupId] = it;
                });
                for(let k in groupKey){
                    audioDevices.forEach(it=>{
                        if(it.groupId == k && (it.deviceId == "" || it.deviceId == "default")){
                            groupKey[k] = it;
                        }
                    })
                }
                let finalDevices = [];
                for(let k in groupKey){
                    finalDevices.push(groupKey[k]);
                }
                this.audioOptions = finalDevices;
                this.allAudioOptions = audioDevices;
            });
        }
    },
     created: function () {
        if (!sessionStorage.getItem('token')) {
            this.$router.push({path: '/login'});
            return;
        } else {
            this.token = sessionStorage.getItem('token');
        }
        if (sessionStorage.getItem('store')) {
            this.storeInfo = JSON.parse(sessionStorage.getItem('store'));
        };

        if ( localStorage.getItem('autoPrint')&&JSON.parse(localStorage.getItem('autoPrint')).autoPrint == 'ON' ) {
            this.printsBtn = true;
        } else if ( localStorage.getItem('autoPrint')&&JSON.parse(localStorage.getItem('autoPrint')).autoPrint == 'OFF' ) {
            this.printsBtn = false;
        } else {
            this.printsBtn = true;
            localStorage.setItem('autoPrint', JSON.stringify({autoPrint:'ON',placingOrder:1,watingOrder:1,exWork:1}));
        }
        // 开班信息
        if (sessionStorage.getItem('workshift')) {
            this.employeeInfo = JSON.parse(sessionStorage.getItem('workshift'));
        };
        // 订单音乐
        if ( localStorage.getItem('orderVoiceName') ) {
            this.curVoiceName = localStorage.getItem('orderVoiceName');
        } else {
            localStorage.setItem('orderVoiceName', 'voice_1.ogg');
        }

        if(!localStorage.getItem('totalClassify')){
            localStorage.setItem('totalClassify', 'DETAILARRTYPE');
        }
        // 设置厨房打印份数
        if(!localStorage.getItem('kitchPrintCount')){
            localStorage.setItem('kitchPrintCount', '2');
        }

        if (!this.storeInfo.storeId) {
            return;
        }
        this.getPosSetting(this.storeInfo.storeId);
        // 
        // 获取店铺信息判断是否选择三方支付
        this.$http.get('/stores/'+this.storeInfo.storeId).then((res)=>{
            if(res.data.makeEnabled && new Date(res.data.makeEndTime).getTime() > new Date().getTime()){
                localStorage.setItem("makeEnabled",1)
            }else{
                localStorage.setItem("makeEnabled",-1)
            }
            this.offOnVoiceNotify = res.data.offOnVoiceNotify;
            this.voiceEnabled = res.data.voiceEnabled;
            this.isPrintPrev = res.data.preEnabled;
            // 
            if (sessionStorage.getItem('token') && res.data.voiceEnabled) {
                try {
                    this.testSelAudio();
                } catch (error) {
                    console.log(error);
                }
            }
            //
            if ( res.data.payMode == "THIRD_PARTY" ) {
                this.isOnline = true;
            } else {
                this.isOnline = false;
            }
            sessionStorage.setItem("rechargeLimit",JSON.stringify(res.data.rechargeLimit));
            sessionStorage.setItem("refundPswEnabled",JSON.stringify(res.data.refundPswEnabled));
            if(res.data.leaseProductEnabled){
                this.leaseProductEnabled = res.data.leaseProductEnabled;
                sessionStorage.setItem("leaseProductEnabled",JSON.stringify(res.data.leaseProductEnabled));
                if(res.data.leaseEndDate){
                    if(new Date().getTime()>new Date(res.data.leaseEndDate).getTime()){
                        sessionStorage.setItem("leaseProductEnabled","false");
                    }else{
                        sessionStorage.setItem("leaseProductEnabled",JSON.stringify(res.data.leaseProductEnabled));
                    }
                }
            }else{
                this.leaseProductEnabled = false;
                sessionStorage.setItem("leaseProductEnabled","false");
            }
            sessionStorage.setItem("returnCallEnabled",JSON.stringify(res.data.returnCallEnabled));

            sessionStorage.setItem("discount",JSON.stringify(res.data.discount));
            sessionStorage.setItem("zero",JSON.stringify(res.data.zero));
            sessionStorage.setItem("chainEnabled",JSON.stringify(res.data.chainEnabled));
            sessionStorage.setItem("offOnVoiceNotify",JSON.stringify(res.data.offOnVoiceNotify));
            sessionStorage.setItem("offOnVoiceMessage",res.data.offOnVoiceMessage);

            sessionStorage.setItem("expireEnabled",JSON.stringify(res.data.expireEnabled));
            sessionStorage.setItem("allowProductCancelSale",JSON.stringify(res.data.allowProductCancelSale));


            let endTime = new Date( new Date( new Date(res.data.expireTime).getTime() + ( 1000 * 60 * 60 * 24 ) ).Format("yyyy/MM/dd 12:00:00") ).getTime();

            console.log("endTime",endTime)
            
            this.endTime = new Date(endTime).Format('yyyy-MM-dd hh:mm:ss');

            sessionStorage.setItem("endTime",JSON.stringify(this.endTime));

            console.log("endDate",this.endTime);

            let nowTime = new Date().getTime();
            
            let endDay = Math.floor((endTime - nowTime) / ( 1000 * 60 * 60 * 24 ));
            this.endDay = endDay;

            if(endDay<0){
                this.$router.push({path:'/login'});
                this.$message.error({
                    message: "店铺已过期，请联系火星捕手销售人员进行续费。",
                    customClass: 'error',
                    duration:19000
                });
                return;
            }

            if(endDay<=7){
                this.$confirm(`店铺还有${endDay}天过期,请联系火星捕手销售人员进行续费。`,'注意', {
                    confirmButtonText: '确定',
                    cancelButtonText: '关闭',
                    type: 'warning',
                    customClass:'beforeExit'
                }).then(() => {
                    
                }).catch((v) => {

                });
                return;
            }

        })
        this.updatesTime = new Date(+JSON.parse(sessionStorage.getItem('workshift')).beginTime).toISOString().replace(/T/g, 'T').replace(/\.[\d]{3}Z/, 'Z');//tz时间
        this.noticeUpdatesTime = new Date(+JSON.parse(sessionStorage.getItem('workshift')).beginTime).toISOString().replace(/T/g, 'T').replace(/\.[\d]{3}Z/, 'Z');//tz时间
        // this.updatesCount();

        // 获得时间
        let date = new Date();
        let weekArr = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        this.dateStr = date.toLocaleDateString();
        // 如果是ie浏览器
        if ( !!window.ActiveXObject || "ActiveXObject" in window ) {

        } else {
            let dateStrSplit = this.dateStr.split('/');
            this.dateStr = dateStrSplit[0] + //年
                        "-"+ (dateStrSplit[1]<10 ? '0' + dateStrSplit[1] : dateStrSplit[1])+ //月
                        "-"+ (dateStrSplit[2]<10 ? '0' + dateStrSplit[2] : dateStrSplit[2]) //日
        }

        this.weekStr = weekArr[date.getDay()];
        this.timeStr = (date.getHours()<10?('0'+date.getHours()):date.getHours()) + ':' + (date.getMinutes()<10?('0'+date.getMinutes()):date.getMinutes());
        let that = this;
        this.intervalTimer = setInterval(()=>{
            let date = new Date();
            that.timeStr = (date.getHours()<10?('0'+date.getHours()):date.getHours()) + ':' + (date.getMinutes()<10?('0'+date.getMinutes()):date.getMinutes());
        }, 10000)

        // 创建ws连接
        // this.connect();
        // alert('created');

    },
    mounted: async function () {
      // setTimeout(()=>{
      //   this.playVoice(["119"]);
      // },19000)
        try {
            emitter.on("refreshWaitSite",(e)=>{
                this.waitNum = e;
            });
            emitter.on("refreshLeaseNum",(e)=>{
                this.leaseNum = e;
            });
        } catch (error) {
            console.log(error);
        }
        try {
            if(this.storeInfo && this.storeInfo.storeId){
                this.storeName = this.storeInfo.storeName
                this.$http.get('/stores/'+this.storeInfo.storeId).then((res)=>{
                    this.deliveryEnabled = res.data.deliveryEnabled;
                    this.posCallEnabled = res.data.posCallEnabled;
                    // this.isAutoPrintOrder = res.data.autoPrintEnabled;
                });
                // const printDevices = await window.getUsbPrintDeviceList();
                // // vid_0471&pid_0055|vid_0483&pid_070b
                // if(printDevices){
                //     if(printDevices.split("|") && Array.isArray(printDevices.split("|")) && printDevices.split("|").length){
                //         this.printDevices = printDevices.split("|");
                //     }
                // }
                // console.log("getUsbPrintDeviceListPre",printDevices);
                // console.log("getUsbPrintDeviceListAfter",this.printDevices);
            }
        } catch (error) {
            console.log(error);
        }
        
        this.connect();
        try {
            this.getIpArr();
        } catch (error) {
            console.log(error)
        }
        
        $(document).ready(() => {
            let that = this;
            $('.vipCheckList li').hover(function () {
                that.curVipIdx = $(this).index() - 1;
            }, function () {
                that.curVipIdx = 0;
            })
        });
    },
    beforeDestroy: function () {
        // 离开路由时，取消订单
        this.disconnect();
        // this.disconnectNotice();
        clearInterval(this.timer);
        clearInterval(this.timerNotice);
        clearInterval(this.ipTimer);
        clearInterval(this.intervalTimer);
        localStorage.removeItem("orders");
        localStorage.removeItem("pasterName");
        localStorage.removeItem("busyNums");
        sessionStorage.removeItem("store");
        sessionStorage.removeItem("token");
        sessionStorage.removeItem("workshift");
        sessionStorage.removeItem("ordersId");
        sessionStorage.removeItem("curSelectVipData");
    }
  }
</script>
<style lang="scss" scoped>
  @import "index";
  .wen{
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 9px;
    background-color: #e66a6a;
    color: #fff;
    text-align: center;
    line-height: 14px;
    // vertical-align: middle;
    cursor: pointer;
    font-size: 12px;
  }
    .send-box-wrap{
        height:calc(100% - 10px);
        overflow: hidden;
        overflow-y: auto;
        background-color: #fff;
        padding: 10px;
        box-sizing: border-box;
        .coupon-item{
				display: inline-block;
				width: 100%;
				font-size: 14px;
				background-color: #fff;
				box-sizing: border-box;
				border-radius: 9px;
				border:1px solid #c18364;
				margin-top: 12px;
                cursor: pointer;
                position: relative;
				.top{
					display: flex;
					align-items: center;
					padding: 5px 12px;
					text-align: left;
					position: relative;
					.coupon-image{
						width: 60px;
						height: 60px;
						border: 1px solid #f2f2f2;
						img{
							width: 60px;
							height: 60px;
						}
					}
					.coupon-desc{
						width: calc(100% - 60px);
						box-sizing: border-box;
						padding: 12px;
						div{
							width: 100%;
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
						}
						.coupon-name{
                            width: calc(100% - 100px);
							font-weight: bold;
							font-size: 18px;
						}
                        .coupon-type{
                            padding: 10px 0;
                        }
						.time{
							color: #e66a6a;
                            padding-top: 10px;
						}
						
					}
					.circle{
						display: inline-block;
						width: 20px;
						height: 20px;
						border-radius: 10px;
						background-color: #fff;
						position: absolute;
						left: -10px;
						bottom: -10px;
						border-right: 1px solid #c18364;
						&.two{
							left: inherit;
							right: -10px;
    						border-left: 1px solid #c18364;
    						border-right: 1px solid #fff;
						}
					}
				}
				.bottom{
					width: 100%;
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					padding: 12px;
					box-sizing: border-box;
					background-color: rgb(245,245,245);
                    color: #999;
				}
                .dsbt{
                    display: flex;
                    justify-content: flex-end;
                    padding: 10px;
                    position: absolute;
                    top: 0;
                    right: 0;
                    .btn{
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        cursor: pointer;
                        padding: 5px 20px;
                        height: 20px;
                        border-radius: 15px;
                        background: #adabab;
                        color: #fff;
                        margin: 5px 10px;
                        &.dsbt-btn{
                            background-color: #fa7d70;;
                        }
                    }
                }
			}
    }
    .form-wrap{
        .dsbt-coupon-info{
            text-align: center;
            .tit{
                font-size: 18px;
                font-weight: bold;
                color:#db5f32;
            }
            .type,.time,.goods{
                padding: 10px 0;
            }
            .goods{
                display: inline-block;
                width: 80%;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }
        .dsbt-form{
            text-align: center;
            width: 50%;
            margin: 0 auto;
        }
    }
</style>
<style lang="scss">
    .el-drawer__container{
        .el-drawer{
            width: 40%!important;
        }
    }
    .coupon-mask{
        height: 100%;
        .el-dialog{
            .el-dialog__title{
                color: #28c47a;
            }
            height: 50%;
            .el-dialog__body{
                height: calc(100% - 65px);
                overflow: hidden;
                overflow-y: auto;
                padding: 10px;
            }
        }
    }
    .coupon-mask-wrap{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom:0;
        z-index: 99;
        background-color: rgba(0,0,0,.5);
        .send-box-wrap{
            width:50%;
            position: absolute;
            top:50%;
            left: 50%;
            transform: translate(-50%,-50%);
            overflow: hidden;
            overflow-y: auto;
            border-radius: 9px;
            &.one{
                height: 200px;
            }
            &.other{
                height: 375px;
            }
        }
    }
</style>